Skip to content

Commit d600c10

Browse files
authored
docs: fix readme examples (#88)
* fix: readme examples * fix negroni at readme * Update README.md * add http example readme
1 parent f4b59c0 commit d600c10

File tree

3 files changed

+145
-86
lines changed

3 files changed

+145
-86
lines changed

README.md

+103-86
Original file line numberDiff line numberDiff line change
@@ -26,36 +26,35 @@ You can use `jwtmiddleware` with default `net/http` as follows.
2626
package main
2727

2828
import (
29-
"fmt"
30-
"net/http"
29+
"fmt"
30+
"net/http"
3131

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"
3534
)
3635

3736
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+
}
4443
})
4544

4645
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)
5958
}
6059
````
6160

@@ -66,79 +65,97 @@ You can also use it with Negroni as follows:
6665
package main
6766

6867
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"
7870

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+
)
8776

8877
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)
107123
}
108124
````
109125

110126
## Options
111127

112128
````go
129+
// Options is a struct for specifying configuration options for the middleware.
113130
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
142159
}
143160
````
144161

examples/http-example/README.md

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# HTTP example
2+
3+
This is an example of how to use the http middleware.
4+
5+
# Using it
6+
7+
To try this out, first install all dependencies with `go install` and then run `go run main.go` to start the app.
8+
9+
* Call `http://localhost:3000` with a JWT signed with `My Secret` to get a response back.

examples/http-example/main.go

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
7+
jwtmiddleware "github.com/auth0/go-jwt-middleware"
8+
"github.com/form3tech-oss/jwt-go"
9+
)
10+
11+
var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
12+
user := r.Context().Value("user")
13+
fmt.Fprintf(w, "This is an authenticated request")
14+
fmt.Fprintf(w, "Claim content:\n")
15+
for k, v := range user.(*jwt.Token).Claims.(jwt.MapClaims) {
16+
fmt.Fprintf(w, "%s :\t%#v\n", k, v)
17+
}
18+
})
19+
20+
func main() {
21+
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
22+
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
23+
return []byte("My Secret"), nil
24+
},
25+
// When set, the middleware verifies that tokens are signed with the specific signing algorithm
26+
// If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
27+
// Important to avoid security issues described here: https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
28+
SigningMethod: jwt.SigningMethodHS256,
29+
})
30+
31+
app := jwtMiddleware.Handler(myHandler)
32+
http.ListenAndServe("0.0.0.0:3000", app)
33+
}

0 commit comments

Comments
 (0)