-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
73 lines (62 loc) · 1.93 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"strings"
firebase "firebase.google.com/go"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"google.golang.org/api/option"
)
func main() {
allowedOrigins := handlers.AllowedOrigins([]string{"http://localhost:8080"})
allowedMethods := handlers.AllowedMethods([]string{"GET", "POST", "DELETE", "PUT"})
allowedHeaders := handlers.AllowedHeaders([]string{"Authorization"})
r := mux.NewRouter()
r.HandleFunc("/public", public)
r.HandleFunc("/private", authMiddleware(private))
log.Fatal(http.ListenAndServe(":8000", handlers.CORS(allowedOrigins, allowedMethods, allowedHeaders)(r)))
}
func public(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello public!\n"))
}
func private(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello private!\n"))
}
/*
* JWTを検証するミドルウェア
* このミドルウェアでハンドラーをラップしたAPIには検証機能がつく
*/
func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Firebase SDK setup
opt := option.WithCredentialsFile("private-key.json")
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
auth, err := app.Auth(context.Background())
if err != nil {
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
// get of JWT sent from client
authHeader := r.Header.Get("Authorization")
idToken := strings.Replace(authHeader, "Bearer ", "", 1)
// JWT verification
token, err := auth.VerifyIDToken(context.Background(), idToken)
if err != nil {
// If JWT is invalid, do not proceed to Handler
fmt.Printf("error verifying ID token: %v\n", err)
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("error verifying ID token\n"))
return
}
log.Printf("Verified ID token: %v\n", token)
next.ServeHTTP(w, r)
}
}