Skip to content
This repository was archived by the owner on Nov 11, 2024. It is now read-only.

Commit 4c4bb92

Browse files
committed
add some comment, and modify example code
1 parent d2ef3d2 commit 4c4bb92

File tree

7 files changed

+41
-21
lines changed

7 files changed

+41
-21
lines changed

auth_error.go

+3
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,7 @@ var (
6262

6363
// ErrInvalidPubKey indicates the the given public key is invalid
6464
ErrInvalidPubKey = errors.New("public key invalid")
65+
66+
// ErrMissingIdentity identity key and identity value is null
67+
ErrMissingIdentity = errors.New("payload don't have identity key and identity value")
6568
)

auth_jwt.go

+10-5
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ func (mw *GfJWTMiddleware) MiddlewareInit() error {
296296
if mw.Key == nil {
297297
return ErrMissingSecretKey
298298
}
299-
299+
300300
if mw.CacheAdapter != nil {
301301
blacklist.SetAdapter(mw.CacheAdapter)
302302
}
@@ -408,9 +408,14 @@ func (mw *GfJWTMiddleware) LoginHandler(r *ghttp.Request) {
408408
}
409409
}
410410

411+
if _, ok := claims[mw.IdentityKey]; !ok {
412+
mw.unauthorized(r, http.StatusInternalServerError, mw.HTTPStatusMessageFunc(ErrMissingIdentity, r))
413+
return
414+
}
415+
411416
expire := mw.TimeFunc().Add(mw.Timeout)
412417
claims["exp"] = expire.Unix()
413-
claims["orig_iat"] = mw.TimeFunc().Unix()
418+
claims["iat"] = mw.TimeFunc().Unix()
414419
tokenString, err := mw.signedString(token)
415420

416421
if err != nil {
@@ -487,7 +492,7 @@ func (mw *GfJWTMiddleware) RefreshToken(r *ghttp.Request) (string, time.Time, er
487492

488493
expire := mw.TimeFunc().Add(mw.Timeout)
489494
newClaims["exp"] = expire.Unix()
490-
newClaims["orig_iat"] = mw.TimeFunc().Unix()
495+
newClaims["iat"] = mw.TimeFunc().Unix()
491496
tokenString, err := mw.signedString(newToken)
492497

493498
if err != nil {
@@ -537,7 +542,7 @@ func (mw *GfJWTMiddleware) CheckIfTokenExpire(r *ghttp.Request) (jwt.MapClaims,
537542

538543
claims := token.Claims.(jwt.MapClaims)
539544

540-
origIat := int64(claims["orig_iat"].(float64))
545+
origIat := int64(claims["iat"].(float64))
541546

542547
if origIat < mw.TimeFunc().Add(-mw.MaxRefresh).Unix() {
543548
return nil, "", ErrExpiredToken
@@ -559,7 +564,7 @@ func (mw *GfJWTMiddleware) TokenGenerator(data interface{}) (string, time.Time,
559564

560565
expire := mw.TimeFunc().UTC().Add(mw.Timeout)
561566
claims["exp"] = expire.Unix()
562-
claims["orig_iat"] = mw.TimeFunc().Unix()
567+
claims["iat"] = mw.TimeFunc().Unix()
563568
tokenString, err := mw.signedString(token)
564569
if err != nil {
565570
return "", time.Time{}, err

example/api/auth.go

+5-3
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ func init() {
3434
RefreshResponse: RefreshResponse,
3535
LogoutResponse: LogoutResponse,
3636
Unauthorized: Unauthorized,
37-
IdentityHandler: IdentityHandler,
3837
PayloadFunc: PayloadFunc,
38+
IdentityHandler: IdentityHandler,
3939
})
4040
if err != nil {
4141
glog.Fatal("JWT Error:" + err.Error())
@@ -60,10 +60,11 @@ func PayloadFunc(data interface{}) jwt.MapClaims {
6060
return claims
6161
}
6262

63-
// IdentityHandler sets the identity for JWT.
63+
// IdentityHandler get the identity from JWT and set the identity for every request
64+
// Using this function, by r.GetParam("id") get identity
6465
func IdentityHandler(r *ghttp.Request) interface{} {
6566
claims := jwt.ExtractClaims(r)
66-
return claims["id"]
67+
return claims[Auth.IdentityKey]
6768
}
6869

6970
// Unauthorized is used to define customized Unauthorized callback function.
@@ -106,6 +107,7 @@ func LogoutResponse(r *ghttp.Request, code int) {
106107

107108
// Authenticator is used to validate login parameters.
108109
// It must return user data as user identifier, it will be stored in Claim Array.
110+
// if your identityKey is 'id', your user data must have 'id'
109111
// Check error (e) to determine the appropriate error message.
110112
func Authenticator(r *ghttp.Request) (interface{}, error) {
111113
var (

example/api/work.go

+18-6
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,31 @@
11
package api
22

33
import (
4+
"github.com/gogf/gf/frame/g"
45
"github.com/gogf/gf/net/ghttp"
56
)
67

78
var Work = new(workApi)
89

910
type workApi struct{}
1011

11-
// hello should be authenticated to view.
12-
func (a *workApi) Hello(r *ghttp.Request) {
13-
r.Response.Write("Hello")
14-
}
15-
1612
// works is the default router handler for web server.
1713
func (a *workApi) Works(r *ghttp.Request) {
18-
r.Response.Write("It works!")
14+
data := g.Map{
15+
"message": "It works!",
16+
}
17+
r.Response.WriteJson(data)
18+
}
19+
20+
// info should be authenticated to view.
21+
// info is the get user data handler
22+
func (a *workApi) Info(r *ghttp.Request) {
23+
data := g.Map{
24+
// get identity by identity key 'id'
25+
"id": r.Get("id"),
26+
"identity_key": r.Get(Auth.IdentityKey),
27+
// get payload by identity
28+
"payload": r.Get("JWT_PAYLOAD"),
29+
}
30+
r.Response.WriteJson(data)
1931
}

example/main.go

+1-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"github.com/gogf/gf-jwt/example/service"
66
"github.com/gogf/gf/frame/g"
77
"github.com/gogf/gf/net/ghttp"
8-
"time"
98
)
109

1110
// authHook is the HOOK function implements JWT logistics.
@@ -15,15 +14,14 @@ func middlewareAuth(r *ghttp.Request) {
1514
}
1615

1716
func main() {
18-
println(time.Now().Unix())
1917
s := g.Server()
2018
s.BindHandler("/", api.Work.Works)
2119
s.BindHandler("POST:/login", api.Auth.LoginHandler)
2220
s.Group("/user", func(g *ghttp.RouterGroup) {
2321
g.Middleware(service.Middleware.CORS, middlewareAuth)
22+
g.ALL("/info", api.Work.Info)
2423
g.ALL("/refresh_token", api.Auth.RefreshHandler)
2524
g.ALL("/logout", api.Auth.LogoutHandler)
26-
g.ALL("/hello", api.Work.Hello)
2725
})
2826
s.SetPort(8000)
2927
s.Run()

example/model/auth.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@ package model
22

33
/**
44
API
5-
*/
5+
*/
66
type ApiLoginReq struct {
77
Username string
88
Password string
99
}
1010

1111
/**
1212
Service
13-
*/
13+
*/
1414
type ServiceLoginReq struct {
1515
Username string
1616
Password string

example/service/user.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@ import (
77

88
var User = new(userService)
99

10-
type userService struct {}
10+
type userService struct{}
1111

1212
func (s *userService) GetUserByUsernamePassword(serviceReq *model.ServiceLoginReq) map[string]interface{} {
1313
if serviceReq.Username == "admin" && serviceReq.Password == "admin" {
1414
return g.Map{
15-
"id": 1,
15+
"id": 1,
1616
"username": "admin",
1717
}
1818
}

0 commit comments

Comments
 (0)