Skip to content

Commit de5dfd7

Browse files
committed
feat: add jwt custom auth to grpc
1 parent 69b4dc3 commit de5dfd7

File tree

11 files changed

+600
-228
lines changed

11 files changed

+600
-228
lines changed

internal/server/grpc.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -171,8 +171,11 @@ func (s *grpcServer) unaryServerOptions() grpc.ServerOption {
171171

172172
// jwt token interceptor
173173
//unaryServerInterceptors = append(unaryServerInterceptors, interceptor.UnaryServerJwtAuth(
174-
// // set ignore rpc methods(full path) for jwt token
175-
// interceptor.WithAuthIgnoreMethods("/api.user.v1.User/Register", "/api.user.v1.User/Login"),
174+
// // choose a verification method as needed
175+
//interceptor.WithStandardVerify(standardVerifyFn), // standard verify (default), you can set standardVerifyFn to nil if you don't need it
176+
//interceptor.WithCustomVerify(customVerifyFn), // custom verify
177+
// // specify the grpc API to ignore token verification(full path)
178+
//interceptor.WithAuthIgnoreMethods("/api.user.v1.User/Register", "/api.user.v1.User/Login"),
176179
//))
177180

178181
// metrics interceptor
@@ -230,7 +233,10 @@ func (s *grpcServer) streamServerOptions() grpc.ServerOption {
230233

231234
// jwt token interceptor
232235
//streamServerInterceptors = append(streamServerInterceptors, interceptor.StreamServerJwtAuth(
233-
// // set ignore rpc methods(full path) for jwt token
236+
// // choose a verification method as needed
237+
//interceptor.WithStandardVerify(standardVerifyFn), // standard verify (default), you can set standardVerifyFn to nil if you don't need it
238+
//interceptor.WithCustomVerify(customVerifyFn), // custom verify
239+
// // specify the grpc API to ignore token verification(full path)
234240
// interceptor.WithAuthIgnoreMethods("/api.user.v1.User/Register", "/api.user.v1.User/Login"),
235241
//))
236242

internal/service/userExample_client_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ func Test_service_userExample_methods(t *testing.T) {
2020
conn := getRPCClientConnForTest()
2121
cli := serverNameExampleV1.NewUserExampleClient(conn)
2222
ctx, _ := context.WithTimeout(context.Background(), time.Second*3)
23-
//ctx = interceptor.SetJwtTokenToCtx(ctx, "Bearer jwt-token-value")
23+
//ctx = interceptor.SetJwtTokenToCtx(ctx, token)
2424

2525
tests := []struct {
2626
name string

pkg/gin/middleware/README.md

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -74,14 +74,17 @@ Adaptive flow limitation based on hardware resources.
7474
import "github.com/zhufuyi/sponge/pkg/gin/middleware"
7575

7676
r := gin.Default()
77-
r.Use(middleware.CircuitBreaker())
77+
r.Use(middleware.CircuitBreaker(
78+
//middleware.WithValidCode(http.StatusRequestTimeout), // add error code 408 for circuit breaker
79+
//middleware.WithDegradeHandler(handler), // add custom degrade handler
80+
))
7881
```
7982

8083
<br>
8184

8285
### jwt authorization middleware
8386

84-
#### common authorization
87+
#### standard authorization
8588

8689
```go
8790
import "github.com/zhufuyi/sponge/pkg/jwt"
@@ -91,8 +94,8 @@ func main() {
9194
r := gin.Default()
9295

9396
r.POST("/user/login", Login)
94-
r.GET("/user/:id", middleware.Auth(), h.GetByID) // no verify field
95-
// r.GET("/user/:id", middleware.Auth(middleware.WithVerify(adminVerify)), h.GetByID) // with verify field
97+
r.GET("/user/:id", middleware.Auth(), h.GetByID) // do not get claims
98+
// r.GET("/user/:id", middleware.Auth(middleware.WithVerify(adminVerify)), h.GetByID) // get claims and check
9699

97100
r.Run(serverAddr)
98101
}
@@ -127,38 +130,35 @@ func main() {
127130
r := gin.Default()
128131

129132
r.POST("/user/login", Login)
130-
r.GET("/user/:id", middleware.AuthCustom(verify), h.GetByID)
133+
r.GET("/user/:id", middleware.AuthCustom(verify), h.GetByID) // get claims and check
131134

132135
r.Run(serverAddr)
133136
}
134137

138+
// custom verify example
135139
func verify(claims *jwt.CustomClaims, tokenTail10 string, c *gin.Context) error {
136140
err := errors.New("verify failed")
137141

138-
// token, fields := getToken(id) // from cache or database
142+
token, fields := getToken(id) // from cache or database
139143
// if tokenTail10 != token[len(token)-10:] { return err }
140-
141-
id, exist := claims.Get("id")
142-
if !exist {
143-
return err
144-
}
145-
foo, exist := claims.Get("foo")
146-
if !exist {
147-
return err
148-
}
149-
if int(id.(float64)) != fields["id"].(int) ||
150-
foo.(string) != fields["foo"].(string) {
151-
return err
152-
}
144+
145+
id, exist := claims.GetUint64("id")
146+
if !exist || id != fields["id"].(uint64) { return err }
147+
148+
name, exist := claims.GetString("name")
149+
if !exist || name != fields["name"].(string) { return err }
150+
151+
age, exist := claims.GetInt("age")
152+
if !exist || age != fields["age"].(int) { return err }
153153

154154
return nil
155155
}
156156

157157
func Login(c *gin.Context) {
158158
// generate token
159-
fields := jwt.KV{"id": 123, "foo": "bar"}
159+
fields := jwt.KV{"id": uint64(123), "name": "tom", "age": 10}
160160
token, err := jwt.GenerateCustomToken(fields)
161-
// save token end fields
161+
// save token and fields
162162
}
163163
```
164164

pkg/gin/middleware/auth.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ func responseUnauthorized(c *gin.Context, isSwitchHTTPCode bool) {
6060

6161
// -------------------------------------------------------------------------------------------
6262

63-
// VerifyFn verify function, tokenTail10 is a string that intercepts the last 10 characters of the token.
63+
// VerifyFn verify function, tokenTail10 is the last 10 characters of the token.
6464
type VerifyFn func(claims *jwt.Claims, tokenTail10 string, c *gin.Context) error
6565

6666
// Auth authorization
@@ -105,7 +105,7 @@ func Auth(opts ...JwtOption) gin.HandlerFunc {
105105

106106
// -------------------------------------------------------------------------------------------
107107

108-
// VerifyCustomFn verify custom function, tokenTail10 is a string that intercepts the last 10 characters of the token.
108+
// VerifyCustomFn verify custom function, tokenTail10 is the last 10 characters of the token.
109109
type VerifyCustomFn func(claims *jwt.CustomClaims, tokenTail10 string, c *gin.Context) error
110110

111111
// AuthCustom custom authentication

0 commit comments

Comments
 (0)