forked from auth0/go-jwt-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
56 lines (42 loc) · 1.17 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
package main
import (
"encoding/json"
"github.com/auth0/go-jwt-middleware"
"github.com/dgrijalva/jwt-go"
"github.com/go-martini/martini"
"net/http"
)
func main() {
StartServer()
}
func StartServer() {
m := martini.Classic()
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte("My Secret"), nil
},
SigningMethod: jwt.SigningMethodHS256,
})
m.Get("/ping", PingHandler)
m.Get("/secured/ping", jwtMiddleware.CheckJWT, SecuredPingHandler)
m.Run()
}
type Response struct {
Text string `json:"text"`
}
func respondJson(text string, w http.ResponseWriter) {
response := Response{text}
jsonResponse, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonResponse)
}
func PingHandler(w http.ResponseWriter, r *http.Request) {
respondJson("All good. You don't need to be authenticated to call this", w)
}
func SecuredPingHandler(w http.ResponseWriter, r *http.Request) {
respondJson("All good. You only get this message if you're authenticated", w)
}