/
auth.go
116 lines (98 loc) · 2.2 KB
/
auth.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
package common
import (
"io/ioutil"
"log"
"net/http"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
// 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
)
// Read the key files before starting http handlers
func initKeys() {
var err error
signKey, err = ioutil.ReadFile(privKeyPath)
if err != nil {
log.Fatalf("[initKeys]: %s\n", err)
}
verifyKey, err = ioutil.ReadFile(pubKeyPath)
if err != nil {
log.Fatalf("[initKeys]: %s\n", err)
panic(err)
}
}
// Generate JWT token
func GenerateJWT(name, role string) (string, error) {
// create a signer for rsa 256
t := jwt.New(jwt.GetSigningMethod("RS256"))
// set claims for JWT token
t.Claims["iss"] = "admin"
t.Claims["UserInfo"] = struct {
Name string
Role string
}{name, role}
// set the expire time for JWT token
t.Claims["exp"] = time.Now().Add(time.Minute * 20).Unix()
tokenString, err := t.SignedString(signKey)
if err != nil {
return "", err
}
return tokenString, nil
}
// Middleware for validating JWT tokens
func Authorize(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
// validate the token
token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
// Verify the token with public key, which is the counter part of private key
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 {
next(w, r)
} else {
DisplayAppError(
w,
err,
"Invalid Access Token",
401,
)
}
}