-
Notifications
You must be signed in to change notification settings - Fork 135
/
jwt.go
139 lines (121 loc) · 3.1 KB
/
jwt.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package apputil
import (
"context"
"crypto/rsa"
"io/ioutil"
"log"
"net/http"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
)
// AppClaims provides custom claim for JWT
type AppClaims struct {
UserName string `json:"username"`
Role string `json:"role"`
jwt.StandardClaims
}
// using asymmetric crypto/RSA keys
// location of private/public key files
const (
// openssl genrsa -out app.rsa 1024
privKeyPath = "keys/app.rsa"
// openssl rsa -in app.rsa -pubout > app.rsa.pub
pubKeyPath = "keys/app.rsa.pub"
)
// Private key for signing and public key for verification
var (
//verifyKey, signKey []byte
verifyKey *rsa.PublicKey
signKey *rsa.PrivateKey
)
// InitRSAKeys reads the key files to be used for JWT
func InitRSAKeys() {
signBytes, err := ioutil.ReadFile(privKeyPath)
if err != nil {
log.Fatalf("[initKeys]: %s\n", err)
}
signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)
if err != nil {
log.Fatalf("[initKeys]: %s\n", err)
}
verifyBytes, err := ioutil.ReadFile(pubKeyPath)
if err != nil {
log.Fatalf("[initKeys]: %s\n", err)
}
verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)
if err != nil {
log.Fatalf("[initKeys]: %s\n", err)
}
}
// GenerateJWT generates a new JWT token for authenticated user.
func GenerateJWT(name, role string) (string, error) {
// Create the Claims
claims := AppClaims{
UserName: name,
Role: role,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Minute * 20).Unix(),
Issuer: "admin",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
ss, err := token.SignedString(signKey)
if err != nil {
return "", err
}
return ss, nil
}
// AuthorizeRequest Middleware validates JWT tokens from incoming HTTP requests.
func AuthorizeRequest(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get token from request
token, err := request.ParseFromRequestWithClaims(r, request.OAuth2Extractor, &AppClaims{}, func(token *jwt.Token) (interface{}, error) {
// since we only use the one private key to sign the tokens,
// we also only use its public counter part to verify
return verifyKey, nil
})
if err != nil {
switch err.(type) {
case *jwt.ValidationError: // JWT validation error
vErr := err.(*jwt.ValidationError)
switch vErr.Errors {
case jwt.ValidationErrorExpired: //JWT expired
DisplayAppError(
w,
err,
"Access Token is expired, get a new Token",
401,
)
return
default:
DisplayAppError(w,
err,
"Error while parsing the Access Token!",
500,
)
return
}
default:
DisplayAppError(w,
err,
"Error while parsing Access Token!",
500)
return
}
}
if token.Valid {
// Create a Context by setting the user name
ctx := context.WithValue(r.Context(), "user", token.Claims.(*AppClaims).UserName)
// Calls the next handler by providing the Context
next.ServeHTTP(w, r.WithContext(ctx))
} else {
DisplayAppError(
w,
err,
"Invalid Access Token",
401,
)
}
})
}