zoukankan      html  css  js  c++  java
  • grpc-golang实现账号and密码认证

    // 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
    }
  • 相关阅读:
    opencv如何载入内存中的图像文件
    C++ 中指针与引用的区别
    2014新版12306接口分析
    Qt 多线程与数据库操作需要注意的几点问题
    设置 Linux 的 LD_LIBRARY_PATH 变量
    linux+Qt程序如何打包发布
    c++(重载、覆盖、隐藏)
    Pytorch中的强化学习
    WordNet简介
    Pytorch中的数学函数
  • 原文地址:https://www.cnblogs.com/xiaouisme/p/7149374.html
Copyright © 2011-2022 走看看