@@ -26,36 +26,35 @@ You can use `jwtmiddleware` with default `net/http` as follows.
26
26
package main
27
27
28
28
import (
29
- " fmt"
30
- " net/http"
29
+ " fmt"
30
+ " net/http"
31
31
32
- " github.com/auth0/go-jwt-middleware"
33
- " github.com/form3tech-oss/jwt-go"
34
- " context"
32
+ " github.com/auth0/go-jwt-middleware"
33
+ " github.com/form3tech-oss/jwt-go"
35
34
)
36
35
37
36
var myHandler = http.HandlerFunc (func (w http.ResponseWriter , r *http.Request ) {
38
- user := r.Context ().Value (" user" )
39
- fmt.Fprintf (w, " This is an authenticated request" )
40
- fmt.Fprintf (w, " Claim content:\n " )
41
- for k , v := range user.(*jwt.Token ).Claims .(jwt.MapClaims ) {
42
- fmt.Fprintf (w, " %s :\t %#v \n " , k, v)
43
- }
37
+ user := r.Context ().Value (" user" )
38
+ fmt.Fprintf (w, " This is an authenticated request" )
39
+ fmt.Fprintf (w, " Claim content:\n " )
40
+ for k , v := range user.(*jwt.Token ).Claims .(jwt.MapClaims ) {
41
+ fmt.Fprintf (w, " %s :\t %#v \n " , k, v)
42
+ }
44
43
})
45
44
46
45
func main () {
47
- jwtMiddleware := jwtmiddleware.New (jwtmiddleware.Options {
48
- ValidationKeyGetter: func (token *jwt.Token ) (interface {}, error ) {
49
- return []byte (" My Secret" ), nil
50
- },
51
- // When set, the middleware verifies that tokens are signed with the specific signing algorithm
52
- // If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
53
- // Important to avoid security issues described here: https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
54
- SigningMethod: jwt.SigningMethodHS256 ,
55
- })
56
-
57
- app := jwtMiddleware.Handler (myHandler)
58
- http.ListenAndServe (" 0.0.0.0:3000" , app)
46
+ jwtMiddleware := jwtmiddleware.New (jwtmiddleware.Options {
47
+ ValidationKeyGetter: func (token *jwt.Token ) (interface {}, error ) {
48
+ return []byte (" My Secret" ), nil
49
+ },
50
+ // When set, the middleware verifies that tokens are signed with the specific signing algorithm
51
+ // If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
52
+ // Important to avoid security issues described here: https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
53
+ SigningMethod: jwt.SigningMethodHS256 ,
54
+ })
55
+
56
+ app := jwtMiddleware.Handler (myHandler)
57
+ http.ListenAndServe (" 0.0.0.0:3000" , app)
59
58
}
60
59
````
61
60
@@ -66,79 +65,97 @@ You can also use it with Negroni as follows:
66
65
package main
67
66
68
67
import (
69
- " context"
70
- " fmt"
71
- " net/http"
72
-
73
- " github.com/auth0/go-jwt-middleware"
74
- " github.com/urfave/negroni"
75
- " github.com/form3tech-oss/jwt-go"
76
- " github.com/gorilla/mux"
77
- )
68
+ " encoding/json"
69
+ " net/http"
78
70
79
- var myHandler = http.HandlerFunc (func (w http.ResponseWriter , r *http.Request ) {
80
- user := r.Context ().Value (" user" );
81
- fmt.Fprintf (w, " This is an authenticated request" )
82
- fmt.Fprintf (w, " Claim content:\n " )
83
- for k , v := range user.(*jwt.Token ).Claims .(jwt.MapClaims ) {
84
- fmt.Fprintf (w, " %s :\t %#v \n " , k, v)
85
- }
86
- })
71
+ " github.com/auth0/go-jwt-middleware"
72
+ " github.com/form3tech-oss/jwt-go"
73
+ " github.com/gorilla/mux"
74
+ " github.com/urfave/negroni"
75
+ )
87
76
88
77
func main () {
89
- r := mux.NewRouter ()
90
-
91
- jwtMiddleware := jwtmiddleware.New (jwtmiddleware.Options {
92
- ValidationKeyGetter: func (token *jwt.Token ) (interface {}, error ) {
93
- return []byte (" My Secret" ), nil
94
- },
95
- // When set, the middleware verifies that tokens are signed with the specific signing algorithm
96
- // If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
97
- // Important to avoid security issues described here: https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
98
- SigningMethod: jwt.SigningMethodHS256 ,
99
- })
100
-
101
- r.Handle (" /ping" , negroni.New (
102
- negroni.HandlerFunc (jwtMiddleware.HandlerWithNext ),
103
- negroni.Wrap (myHandler),
104
- ))
105
- http.Handle (" /" , r)
106
- http.ListenAndServe (" :3001" , nil )
78
+ StartServer ()
79
+ }
80
+
81
+ func StartServer () {
82
+ r := mux.NewRouter ()
83
+
84
+ jwtMiddleware := jwtmiddleware.New (jwtmiddleware.Options {
85
+ ValidationKeyGetter: func (token *jwt.Token ) (interface {}, error ) {
86
+ return []byte (" My Secret" ), nil
87
+ },
88
+ SigningMethod: jwt.SigningMethodHS256 ,
89
+ })
90
+
91
+ r.HandleFunc (" /ping" , PingHandler)
92
+ r.Handle (" /secured/ping" , negroni.New (
93
+ negroni.HandlerFunc (jwtMiddleware.HandlerWithNext ),
94
+ negroni.Wrap (http.HandlerFunc (SecuredPingHandler)),
95
+ ))
96
+ http.Handle (" /" , r)
97
+ http.ListenAndServe (" :3001" , nil )
98
+ }
99
+
100
+ type Response struct {
101
+ Text string ` json:"text"`
102
+ }
103
+
104
+ func respondJSON (text string , w http .ResponseWriter ) {
105
+ response := Response{text}
106
+
107
+ jsonResponse , err := json.Marshal (response)
108
+ if err != nil {
109
+ http.Error (w, err.Error (), http.StatusInternalServerError )
110
+ return
111
+ }
112
+
113
+ w.Header ().Set (" Content-Type" , " application/json" )
114
+ w.Write (jsonResponse)
115
+ }
116
+
117
+ func PingHandler (w http .ResponseWriter , r *http .Request ) {
118
+ respondJSON (" All good. You don't need to be authenticated to call this" , w)
119
+ }
120
+
121
+ func SecuredPingHandler (w http .ResponseWriter , r *http .Request ) {
122
+ respondJSON (" All good. You only get this message if you're authenticated" , w)
107
123
}
108
124
````
109
125
110
126
## Options
111
127
112
128
```` go
129
+ // Options is a struct for specifying configuration options for the middleware.
113
130
type Options struct {
114
- // The function that will return the Key to validate the JWT.
115
- // It can be either a shared secret or a public key.
116
- // Default value: nil
117
- ValidationKeyGetter jwt.Keyfunc
118
- // The name of the property in the request where the user information
119
- // from the JWT will be stored.
120
- // Default value: "user"
121
- UserProperty string
122
- // The function that will be called when there's an error validating the token
123
- // Default value: https://github.com/auth0/go-jwt-middleware/blob/master/jwtmiddleware.go#L35
124
- ErrorHandler errorHandler
125
- // A boolean indicating if the credentials are required or not
126
- // Default value: false
127
- CredentialsOptional bool
128
- // A function that extracts the token from the request
129
- // Default: FromAuthHeader (i.e., from Authorization header as bearer token)
130
- Extractor TokenExtractor
131
- // Debug flag turns on debugging output
132
- // Default: false
133
- Debug bool
134
- // When set, all requests with the OPTIONS method will use authentication
135
- // Default: false
136
- EnableAuthOnOptions bool ,
137
- // When set, the middelware verifies that tokens are signed with the specific signing algorithm
138
- // If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
139
- // Important to avoid security issues described here: https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
140
- // Default: nil
141
- SigningMethod jwt.SigningMethod
131
+ // The function that will return the Key to validate the JWT.
132
+ // It can be either a shared secret or a public key.
133
+ // Default value: nil
134
+ ValidationKeyGetter jwt.Keyfunc
135
+ // The name of the property in the request where the user information
136
+ // from the JWT will be stored.
137
+ // Default value: "user"
138
+ UserProperty string
139
+ // The function that will be called when there's an error validating the token
140
+ // Default value:
141
+ ErrorHandler errorHandler
142
+ // A boolean indicating if the credentials are required or not
143
+ // Default value: false
144
+ CredentialsOptional bool
145
+ // A function that extracts the token from the request
146
+ // Default: FromAuthHeader (i.e., from Authorization header as bearer token)
147
+ Extractor TokenExtractor
148
+ // Debug flag turns on debugging output
149
+ // Default: false
150
+ Debug bool
151
+ // When set, all requests with the OPTIONS method will use authentication
152
+ // Default: false
153
+ EnableAuthOnOptions bool
154
+ // When set, the middelware verifies that tokens are signed with the specific signing algorithm
155
+ // If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
156
+ // Important to avoid security issues described here: https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
157
+ // Default: nil
158
+ SigningMethod jwt.SigningMethod
142
159
}
143
160
````
144
161
0 commit comments