generated from VLADIMIR/template
up
This commit is contained in:
@@ -16,17 +16,19 @@ func NewAuthorizationInterceptor(
|
||||
processorJWT IProcessorJWT,
|
||||
) grpc.UnaryServerInterceptor {
|
||||
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
|
||||
if publicMethods[info.FullMethod] {
|
||||
return handler(ctx, req)
|
||||
}
|
||||
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
if publicMethods[info.FullMethod] {
|
||||
return handler(ctx, req)
|
||||
}
|
||||
return nil, status.Errorf(codes.Unauthenticated, "metadata is not provided")
|
||||
}
|
||||
|
||||
values := md.Get("authorization")
|
||||
if len(values) == 0 {
|
||||
if publicMethods[info.FullMethod] {
|
||||
return handler(ctx, req)
|
||||
}
|
||||
return nil, status.Errorf(codes.Unauthenticated, "authorization token is not provided")
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package processor_jwt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
type testProcessor struct{}
|
||||
|
||||
func (testProcessor) GetClaims(string) (*JWTClaims, error) {
|
||||
return &JWTClaims{Roles: []string{"admin"}}, nil
|
||||
}
|
||||
|
||||
func (testProcessor) GenerateAccessToken(int, string, []string) (string, error) { return "", nil }
|
||||
func (testProcessor) GenerateRefreshToken(int) (string, error) { return "", nil }
|
||||
|
||||
func TestAuthorizationInterceptorAddsClaimsToPublicMethod(t *testing.T) {
|
||||
interceptor := NewAuthorizationInterceptor(map[string]bool{"/public": true}, testProcessor{})
|
||||
ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs("authorization", "Bearer token"))
|
||||
|
||||
_, err := interceptor(ctx, nil, &grpc.UnaryServerInfo{FullMethod: "/public"}, func(ctx context.Context, _ any) (any, error) {
|
||||
claims, ok := ClaimsFromContext(ctx)
|
||||
if !ok || !claims.HasRole("admin") {
|
||||
t.Fatalf("claims = %#v, want admin claims", claims)
|
||||
}
|
||||
return nil, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user