向宁 3eb1a1839d feat: add JWT auth middleware with public endpoint selector
Add HS256 JWT authentication to both HTTP and gRPC servers using
Kratos jwt middleware with selector to skip auth for public share
endpoints (GetShareInfo, DownloadShare). Wire DI updated to inject
conf.Auth into server constructors.
2026-05-25 13:43:34 +08:00

58 lines
1.6 KiB
Go

package server
import (
"context"
pb "rag/file-system/api/file/v1"
"rag/file-system/internal/conf"
"rag/file-system/internal/service"
jwtv5 "github.com/golang-jwt/jwt/v5"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/middleware/auth/jwt"
"github.com/go-kratos/kratos/v2/middleware/logging"
"github.com/go-kratos/kratos/v2/middleware/recovery"
"github.com/go-kratos/kratos/v2/middleware/selector"
"github.com/go-kratos/kratos/v2/middleware/tracing"
kgrpc "github.com/go-kratos/kratos/v2/transport/grpc"
)
func NewGRPCServer(c *conf.Server, auth *conf.Auth, svc *service.FileService, logger log.Logger) *kgrpc.Server {
jwtMiddleware := jwt.Server(
func(token *jwtv5.Token) (interface{}, error) {
return []byte(auth.GetJwtKey()), nil
},
)
// Selector: apply JWT to all routes EXCEPT public share endpoints
authSelector := selector.Server(jwtMiddleware).Match(func(ctx context.Context, operation string) bool {
switch operation {
case "/api.file.v1.FileService/GetShareInfo",
"/api.file.v1.FileService/DownloadShare":
return false // skip JWT for public share access
default:
return true // apply JWT to all other endpoints
}
}).Build()
opts := []kgrpc.ServerOption{
kgrpc.Middleware(
recovery.Recovery(),
tracing.Server(),
logging.Server(logger),
authSelector,
),
}
if c != nil && c.Grpc != nil {
if c.Grpc.Addr != "" {
opts = append(opts, kgrpc.Address(c.Grpc.Addr))
}
if c.Grpc.Timeout != nil {
opts = append(opts, kgrpc.Timeout(c.Grpc.Timeout.AsDuration()))
}
}
srv := kgrpc.NewServer(opts...)
pb.RegisterFileServiceServer(srv, svc)
return srv
}