forked from shijuvar/go-recipes
-
Notifications
You must be signed in to change notification settings - Fork 2
/
auth.go
152 lines (132 loc) · 3.33 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package common
import (
"crypto/rsa"
"errors"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
"github.com/gorilla/context"
)
// 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
)
// Read the key files before starting http handlers
func initKeys() {
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{
name,
role,
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
}
// Authorize Middleware validates JWT tokens if incoming HTTP requests.
func Authorize(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
// 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 {
// Set user name to HTTP context
context.Set(r, "user", token.Claims.(*AppClaims).UserName)
next(w, r)
} else {
DisplayAppError(
w,
err,
"Invalid Access Token",
401,
)
}
}
// TokenFromAuthHeader is a "TokenExtractor" that takes a given request and extracts
// the JWT token from the Authorization header.
func TokenFromAuthHeader(r *http.Request) (string, error) {
// Look for an Authorization header
if ah := r.Header.Get("Authorization"); ah != "" {
// Should be a bearer token
if len(ah) > 6 && strings.ToUpper(ah[0:6]) == "BEARER" {
return ah[7:], nil
}
}
return "", errors.New("No token in the HTTP request")
}