首页 > 代码库 > grpc-golang实现账号and密码认证
grpc-golang实现账号and密码认证
// I would recommend to use interceptors:// clientgrpc.Dial(target, grpc.WithPerRPCCredentials(&loginCreds{ Username: "admin", Password: "admin123",}))type loginCreds struct { Username, Password string}func (c *loginCreds) GetRequestMetadata(context.Context, ...string) (map[string]string, error) { return map[string]string{ "username": c.Username, "password": c.Password, }, nil}func (c *loginCreds) RequireTransportSecurity() bool { return true}// servergrpc.NewServer( grpc.StreamInterceptor(streamInterceptor), grpc.UnaryInterceptor(unaryInterceptor))func streamInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if err := authorize(stream.Context()); err != nil { return err } return handler(srv, stream)}func unaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { if err := authorize(ctx); err != nil { return err } return handler(ctx, req)}func authorize(ctx context.Context) error { if md, ok := metadata.FromContext(ctx); ok { if len(md["username"]) > 0 && md["username"][0] == "admin" && len(md["password"]) > 0 && md["password"][0] == "admin123" { return nil } return AccessDeniedErr } return EmptyMetadataErr}
grpc-golang实现账号and密码认证
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。