Skip to content

Commit 18c7770

Browse files
authored
feat: Make gin-jwt return Authorization headers (#149)
fix #108
1 parent 9ad0d88 commit 18c7770

File tree

2 files changed

+48
-6
lines changed

2 files changed

+48
-6
lines changed

auth_jwt.go

+9
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,9 @@ type GinJWTMiddleware struct {
107107

108108
// Allow insecure cookies for development over http
109109
SecureCookie bool
110+
111+
// SendAuthorization allow return authorization header for every request
112+
SendAuthorization bool
110113
}
111114

112115
var (
@@ -314,6 +317,12 @@ func (mw *GinJWTMiddleware) middlewareImpl(c *gin.Context) {
314317
return
315318
}
316319

320+
if mw.SendAuthorization {
321+
if v, ok := c.Get("JWT_TOKEN"); ok {
322+
c.Header("Authorization", mw.TokenHeadName+" "+v.(string))
323+
}
324+
}
325+
317326
claims := token.Claims.(jwt.MapClaims)
318327

319328
id := mw.IdentityHandler(claims)

auth_jwt_test.go

+39-6
Original file line numberDiff line numberDiff line change
@@ -595,12 +595,8 @@ func TestAuthorizator(t *testing.T) {
595595
Timeout: time.Hour,
596596
MaxRefresh: time.Hour * 24,
597597
Authenticator: defaultAuthenticator,
598-
Authorizator: func(user interface{}, c *gin.Context) bool {
599-
if user.(string) != "admin" {
600-
return false
601-
}
602-
603-
return true
598+
Authorizator: func(data interface{}, c *gin.Context) bool {
599+
return data.(string) == "admin"
604600
},
605601
}
606602

@@ -989,3 +985,40 @@ func TestHTTPStatusMessageFunc(t *testing.T) {
989985
assert.Equal(t, successMessage, successString)
990986
assert.NotEqual(t, successMessage, failedString)
991987
}
988+
989+
func TestSendAuthorizationBool(t *testing.T) {
990+
// the middleware to test
991+
authMiddleware := &GinJWTMiddleware{
992+
Realm: "test zone",
993+
Key: key,
994+
Timeout: time.Hour,
995+
MaxRefresh: time.Hour * 24,
996+
Authenticator: defaultAuthenticator,
997+
SendAuthorization: true,
998+
Authorizator: func(data interface{}, c *gin.Context) bool {
999+
return data.(string) == "admin"
1000+
},
1001+
}
1002+
1003+
handler := ginHandler(authMiddleware)
1004+
1005+
r := gofight.New()
1006+
1007+
r.GET("/auth/hello").
1008+
SetHeader(gofight.H{
1009+
"Authorization": "Bearer " + makeTokenString("HS256", "test"),
1010+
}).
1011+
Run(handler, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
1012+
assert.Equal(t, http.StatusForbidden, r.Code)
1013+
})
1014+
1015+
r.GET("/auth/hello").
1016+
SetHeader(gofight.H{
1017+
"Authorization": "Bearer " + makeTokenString("HS256", "admin"),
1018+
}).
1019+
Run(handler, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
1020+
token := r.HeaderMap.Get("Authorization")
1021+
assert.Equal(t, "Bearer "+makeTokenString("HS256", "admin"), token)
1022+
assert.Equal(t, http.StatusOK, r.Code)
1023+
})
1024+
}

0 commit comments

Comments
 (0)