• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

_example/H03-Feb-2020-11636

.gitignoreH A D03-Feb-202025 33

.travis.ymlH A D03-Feb-2020288 1713

LICENSEH A D03-Feb-20201.1 KiB2116

README.mdH A D03-Feb-20203.9 KiB11585

jwtauth.goH A D03-Feb-20207.8 KiB279188

jwtauth_test.goH A D03-Feb-20207.9 KiB302229

README.md

1# jwtauth - JWT authentication middleware for Go HTTP services
2
3[![GoDoc Widget]][godoc]
4
5The `jwtauth` http middleware package provides a simple way to verify a JWT token
6from a http request and send the result down the request context (`context.Context`).
7
8Please note, `jwtauth` works with any Go http router, but resides under the go-chi group
9for maintenance and organization - its only 3rd party dependency is the underlying jwt library
10"github.com/dgrijalva/jwt-go".
11
12This package uses the new `context` package in Go 1.7 stdlib and [net/http#Request.Context](https://golang.org/pkg/net/http/#Request.Context) to pass values between handler chains.
13
14In a complete JWT-authentication flow, you'll first capture the token from a http
15request, decode it, verify it and then validate that its correctly signed and hasn't
16expired - the `jwtauth.Verifier` middleware handler takes care of all of that. The
17`jwtauth.Verifier` will set the context values on keys `jwtauth.TokenCtxKey` and
18`jwtauth.ErrorCtxKey`.
19
20Next, it's up to an authentication handler to respond or continue processing after the
21`jwtauth.Verifier`. The `jwtauth.Authenticator` middleware responds with a 401 Unauthorized
22plain-text payload for all unverified tokens and passes the good ones through. You can
23also copy the Authenticator and customize it to handle invalid tokens to better fit
24your flow (ie. with a JSON error response body).
25
26By default, the `Verifier` will search for a JWT token in a http request, in the order:
27
281.  'jwt' URI query parameter
292.  'Authorization: BEARER T' request header
303.  'jwt' Cookie value
31
32The first JWT string that is found as a query parameter, authorization header
33or cookie header is then decoded by the `jwt-go` library and a \*jwt.Token
34object is set on the request context. In the case of a signature decoding error
35the Verifier will also set the error on the request context.
36
37The Verifier always calls the next http handler in sequence, which can either
38be the generic `jwtauth.Authenticator` middleware or your own custom handler
39which checks the request context jwt token and error to prepare a custom
40http response.
41
42Note: jwtauth supports custom verification sequences for finding a token
43from a request by using the `Verify` middleware instantiator directly. The default
44`Verifier` is instantiated by calling `Verify(ja, TokenFromQuery, TokenFromHeader, TokenFromCookie)`.
45
46# Usage
47
48See the full [example](https://github.com/go-chi/jwtauth/blob/master/_example/main.go).
49
50```go
51package main
52
53import (
54	"fmt"
55	"net/http"
56
57	"github.com/go-chi/chi"
58	"github.com/go-chi/jwtauth"
59)
60
61var tokenAuth *jwtauth.JWTAuth
62
63func init() {
64	tokenAuth = jwtauth.New("HS256", []byte("secret"), nil)
65
66	// For debugging/example purposes, we generate and print
67	// a sample jwt token with claims `user_id:123` here:
68	_, tokenString, _ := tokenAuth.Encode(jwt.MapClaims{"user_id": 123})
69	fmt.Printf("DEBUG: a sample jwt is %s\n\n", tokenString)
70}
71
72func main() {
73	addr := ":3333"
74	fmt.Printf("Starting server on %v\n", addr)
75	http.ListenAndServe(addr, router())
76}
77
78func router() http.Handler {
79	r := chi.NewRouter()
80
81	// Protected routes
82	r.Group(func(r chi.Router) {
83		// Seek, verify and validate JWT tokens
84		r.Use(jwtauth.Verifier(tokenAuth))
85
86		// Handle valid / invalid tokens. In this example, we use
87		// the provided authenticator middleware, but you can write your
88		// own very easily, look at the Authenticator method in jwtauth.go
89		// and tweak it, its not scary.
90		r.Use(jwtauth.Authenticator)
91
92		r.Get("/admin", func(w http.ResponseWriter, r *http.Request) {
93			_, claims, _ := jwtauth.FromContext(r.Context())
94			w.Write([]byte(fmt.Sprintf("protected area. hi %v", claims["user_id"])))
95		})
96	})
97
98	// Public routes
99	r.Group(func(r chi.Router) {
100		r.Get("/", func(w http.ResponseWriter, r *http.Request) {
101			w.Write([]byte("welcome anonymous"))
102		})
103	})
104
105	return r
106}
107```
108
109# LICENSE
110
111[MIT](/LICENSE)
112
113[godoc]: https://godoc.org/github.com/go-chi/jwtauth
114[godoc widget]: https://godoc.org/github.com/go-chi/jwtauth?status.svg
115