From d2977ce4d9f6ecc3cf90aed5fc085c7426b13594 Mon Sep 17 00:00:00 2001 From: Nikolai Rodionov Date: Tue, 28 Apr 2026 13:46:52 +0200 Subject: [PATCH] Access token auth implemented Signed-off-by: Nikolai Rodionov --- internal/interceptors/authjwt.go | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/internal/interceptors/authjwt.go b/internal/interceptors/authjwt.go index ce778eb..30eca99 100644 --- a/internal/interceptors/authjwt.go +++ b/internal/interceptors/authjwt.go @@ -2,11 +2,14 @@ package interceptors import ( "context" + "fmt" "strings" "gitea.badhouseplants.net/softplayer/softplayer-backend/internal/tools/logger" + "github.com/golang-jwt/jwt/v5" "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) @@ -32,7 +35,25 @@ func (v *JWTVerifier) JWTAuthInterceptor( log := logger.FromContext(v.serverCtx).WithValues("method", info.FullMethod) if !strings.Contains(info.FullMethod, "NoAuth") { log.Info("Checking the JWT token") - return nil, status.Error(codes.Unauthenticated, "Use is not authorized") + md, ok := metadata.FromIncomingContext(ctx) + if !ok { + return nil, status.Error(codes.Unauthenticated, "User is not authorized") + } + + tokenString := md.Get("token")[0] + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { + // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key") + return v.secret, nil + }, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()})) + if err != nil { + return nil, status.Error(codes.Unauthenticated, "User is not authorized") + } + + if claims, ok := token.Claims.(jwt.MapClaims); ok { + fmt.Println(claims["userID"]) + } else { + fmt.Println(err) + } // Get the token from the metadata // Validate the token // Get the user id from the token