码迷,mamicode.com
首页 > 其他好文 > 详细

grpc-golang实现账号and密码认证

时间:2017-07-11 11:10:32      阅读:871      评论:0      收藏:0      [点我收藏+]

标签:author   ror   password   server   bsp   ext   ret   name   uri   

// I would recommend to use interceptors:

// client
grpc.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
}

// server
grpc.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密码认证

标签:author   ror   password   server   bsp   ext   ret   name   uri   

原文地址:http://www.cnblogs.com/xiaouisme/p/7149374.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!