var authFunc grpc_auth.AuthFunc
{
authFunc = func(ctx context.Context) (context.Context, error) {
logger.Debug("platform authfun run !")
token, err := tools.ParseJwtToken(ctx)
if err != nil {
return nil, ErrMiddlewareParseJwtFailure
}
client, err := cli.NewAuthClient(zap.NewExample(), AuthUrl, false)
if err != nil {
return nil, ErrInitAuthClient
}
_, err = client.ValidateToken(ctx, token)
// ValidateToken已对err封装
if err != nil {
return nil, err
}
logger.Debug("platform middleware authfun run over , Check passed !")
return ctx, nil
}
}
将grpc_auth加入到middleware中
重写authFunc,存在AuthFuncOverride则不会调用authfunc,需要将其配置到注册服务里。
func (s *Service)AuthFuncOverride(ctx context.Context, fullMethodName string) (context.Context, error) {
if fullMethodName == MethodValidateToken || fullMethodName == MethodAuthenticate{
return ctx, nil
}
s.logger.Debug("authfun run , client is calling method:" + fullMethodName)
token, err := tools.ParseJwtToken(ctx)
if err != nil {
return ctx, ErrMiddlewareParseJwtFailure
}
_, err = s.ValidateToken(ctx, &pb.ValidateTokenRequest{
JwtToken: token,
})
// ValidateToken 中已经对err进行封装
if err != nil {
return ctx, err
}
s.logger.Debug("platform middleware authfun run over , check passed !")
return ctx, nil
}
-
参考:https://www.cnblogs.com/FireworksEasyCool/p/12750339.html
-
参考:https://godoc.org/github.com/grpc-ecosystem/go-grpc-middleware/auth