-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathjwt.go
179 lines (157 loc) · 5.03 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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package middlewares
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/twreporter/go-api/globals"
"github.com/twreporter/go-api/utils"
"github.com/auth0/go-jwt-middleware"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
const authUserProperty = "app-auth-jwt"
var jwtMiddleware = jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte(globals.Conf.App.JwtSecret), nil
},
UserProperty: authUserProperty,
SigningMethod: jwt.SigningMethodHS256,
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err string) {
var res = map[string]interface{}{
"status": "fail",
"data": map[string]interface{}{
"req.Headers.Authorization": err,
},
}
var resByte, _ = json.Marshal(res)
http.Error(w, string(resByte), http.StatusUnauthorized)
},
})
func PassAuthUserID() gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Header["Authorization"] == nil {
return
}
if err := jwtMiddleware.CheckJWT(c.Writer, c.Request); err != nil {
return
}
userProperty := c.Request.Context().Value(authUserProperty)
claims := userProperty.(*jwt.Token).Claims.(jwt.MapClaims)
// Set user_id with key "auth-user-id" in context to avoid hierarchy access
newRequest := c.Request.WithContext(context.WithValue(c.Request.Context(), globals.AuthUserIDProperty, claims["user_id"]))
*c.Request = *newRequest
}
}
// ValidateAuthorization checks the jwt token in the Authorization header is valid or not
func ValidateAuthorization() gin.HandlerFunc {
return func(c *gin.Context) {
const verifyRequired = true
var err error
var userProperty interface{}
var claims jwt.MapClaims
if err = jwtMiddleware.CheckJWT(c.Writer, c.Request); err != nil {
c.Abort()
return
}
userProperty = c.Request.Context().Value(authUserProperty)
claims = userProperty.(*jwt.Token).Claims.(jwt.MapClaims)
if !claims.VerifyAudience(globals.Conf.App.JwtAudience, verifyRequired) ||
!claims.VerifyIssuer(globals.Conf.App.JwtIssuer, verifyRequired) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"status": "fail",
"data": gin.H{
"req.Cookies.id_token": "aud or issuer claim is invalid",
},
})
return
}
var newRequest *http.Request
// Set user_id with key "auth-user-id" in context to avoid hierarchy access
newRequest = c.Request.WithContext(context.WithValue(c.Request.Context(), globals.AuthUserIDProperty, claims["user_id"]))
*c.Request = *newRequest
}
}
// ValidateUserID checks claim userID in the jwt with :userID param in the request url.
// if the two values are not the same, return the 401 response
func ValidateUserID() gin.HandlerFunc {
return func(c *gin.Context) {
var (
userID string
authUserID interface{}
)
authUserID = c.Request.Context().Value(globals.AuthUserIDProperty)
userID = c.Param("userID")
if userID != fmt.Sprint(authUserID) {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"status": "fail",
"data": gin.H{
"req.Headers.Authorization": "the request is not permitted to reach the resource",
},
})
}
}
}
func ValidateUserIDInReqBody() gin.HandlerFunc {
return func(c *gin.Context) {
var (
body = struct {
UserID uint64 `json:"user_id" form:"user_id" binding:"required"`
}{}
err error
authUserID interface{}
)
// gin.Context.Bind does not support to bind `JSON` body multiple times
// the alternative is to use gin.Context.ShouldBindBodyWith function to bind
if err = c.ShouldBindBodyWith(&body, binding.JSON); err == nil {
// omit intentionally
} else if err = c.Bind(&body); err != nil {
// bind other format rather than JSON
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"status": "fail", "data": gin.H{
"req.Body.user_id": err.Error(),
}})
return
}
authUserID = c.Request.Context().Value(globals.AuthUserIDProperty)
if fmt.Sprint(body.UserID) != fmt.Sprint(authUserID) {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"status": "fail", "data": gin.H{
"req.Headers.Authorization": "the request is not permitted to reach the resource",
}})
return
}
}
}
// ValidateAuthentication validates `req.Cookies.id_token`
// if id_token, which is a JWT, is invalid, and then return 401 status code
func ValidateAuthentication() gin.HandlerFunc {
return func(c *gin.Context) {
var tokenString string
var err error
var token *jwt.Token
defer func() {
if r := recover(); r != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"status": "fail",
"data": gin.H{
"req.Headers.Cookies.id_token": err.Error(),
},
})
return
}
}()
if tokenString, err = c.Cookie("id_token"); err != nil {
panic(err)
}
if token, err = jwt.ParseWithClaims(tokenString, &utils.IDTokenJWTClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(globals.Conf.App.JwtSecret), nil
}); err != nil {
panic(err)
}
if !token.Valid {
err = errors.New("id_token is invalid")
panic(err)
}
}
}