.netcore grpc身份验证和授权

news/2024/5/19 21:08:15 标签: .netcore, rpc

一、鉴权和授权(grpc专栏结束后会开启鉴权授权专栏欢迎大家关注)

  1. 权限认证这里使用IdentityServer4配合JWT进行认证
  2. 通过AddAuthentication和AddAuthorization方法进行鉴权授权注入;通过UseAuthentication和UseAuthorization启用鉴权授权
  3. 增加授权策略处理
  4. 使用密码模式,及简易内存处理
  5. 生成token带入grpc的metadata进行传递
  6. 服务端对应的方法标记特性[Authorize]进行验证
  7. 代码中会有对应的注释说明,如果对您有用,可静下心来细致的浏览

二、实战案例

  1. 需要一个授权中心服务
  2. 需要一个gRPC后端服务
  3. 需要一个客户端调用对应的授权中心和gRPC后端服务

第一步:授权中心

        1)引入IdentityServer4包

        2)添加IdentityServer注入及启用IdentityServer

// 添加IdentityServer4注入

// 注入id4服务 配置开发证书 配置内存客户端client
builder.Services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryClients(PasswordInfoConfig.GetClients())
                .AddInMemoryApiResources(PasswordInfoConfig.GetApiResources())
                .AddInMemoryApiScopes(PasswordInfoConfig.GetApiScopes())
                .AddTestUsers(PasswordInfoConfig.GetUsers());


// 启用IdentityServer 同时启用认证和授权

app.UseIdentityServer();
app.UseAuthentication();

app.UseAuthorization();

        3)密码 在程序中进行了初始化;因为是模拟,这里就没有放到数据库

    public class PasswordInfoConfig
    {

        /// <summary>
        /// 获取设定客户端
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Client> GetClients()
        {
            return new[] {
                new Client{
                    ClientId="laoliu",
                    ClientSecrets= new []{ new Secret("laoliu123456".Sha256()) },
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                    AllowedScopes = new[] {"TestApi","UserApi"},
                    Claims = new List<ClientClaim>(){
                        new ClientClaim(JwtClaimTypes.Role,"Admin"),
                        new ClientClaim(JwtClaimTypes.NickName,"王先生"),
                        new ClientClaim(JwtClaimTypes.Email,"88@163.com")
                    }
                }
            };

        }

        /// <summary>
        /// 获取Api对应的作用域
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiScope> GetApiScopes()
        {
            return new[] { new ApiScope("UserApi", "用户作用域"), new ApiScope("TestApi", "测试作用域") };
        }

        /// <summary>
        /// 获取Api资源
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new[]
            {
                new ApiResource("TestApi","测试的API",new List<string>{ IdentityModel.JwtClaimTypes.Role,"email"})
                {
                    Scopes = new List<string> { "TestApi" }
                },
                new ApiResource("UserApi","用户的API",new List<string>{ JwtClaimTypes.NickName,"email"})
                {
                    Scopes= new List<string> { "UserApi" }
                }
            };
        }


        public static List<TestUser> GetUsers()
        {
            return new List<TestUser>
            {
                new TestUser()
                {
                    Username="admin",
                    Password="password",
                    SubjectId="0",
                    Claims= new List<Claim>(){
                        new Claim(JwtClaimTypes.Role,"Admin"),
                        new Claim(JwtClaimTypes.NickName,"陈先生"),
                        new Claim(JwtClaimTypes.Email,"77.com")
                    }
                }
            };
        }
    }

第二步:gRPC后端服务

        1)引入IdentityServer4、IdentityServer4.AccessTokenValidation、Microsoft.AspNetCore.Authentication.JwtBearer包

        2)添加IdentityServer权限解析认证

        3)启用鉴权和授权

        4)对应的类或方法中标记 [Authorize]

        4)GRPC的服务及Proto文件这里不贴上来了 有需要可以直接百度云盘下载源码查看

// 注入
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddIdentityServerAuthentication(options =>
                {
                    // 权限中心 服务地址
                    options.Authority = "http://localhost:5172";
                    options.ApiName = "TestApi";
                    options.RequireHttpsMetadata = false;
                });

builder.Services.AddAuthorization();
builder.Services.AddGrpc();

// 启用

app.UseAuthentication();
app.UseAuthorization();

// 字段
app.MapGrpcService<ProtoFieldService>();

// 基础配置
[Authorize]
public override async Task<Empty> BaseConfigService(BaseConfig request, ServerCallContext context)
{
    await Console.Out.WriteLineAsync("\r\n--------------------------基础配置--------------------------\r\n");
    // 打印字段信息
    var properties = request.GetType().GetProperties();
    foreach (var property in properties)
    {
        var value = property.GetValue(request);

        await Console.Out.WriteLineAsync($"{property.Name}:{value}");
    }
    return new Empty();
}

第三步:WPF客户端

        1)调用鉴权中心获取token

        2)gRPC工厂中配置token传递 或者在调用对应的客户端函数中对metadata传参

        3)调用

    public class WpfAuthClient
    {
        private static string _token = null;

        public static async Task<string> GetToken()
        {
            if (_token != null)
            {
                return _token;
            }
            var client = new HttpClient();
            PasswordTokenRequest tokenRequest = new PasswordTokenRequest();
            tokenRequest.Address = "http://localhost:5172/connect/token";
            tokenRequest.GrantType = GrantType.ResourceOwnerPassword;
            tokenRequest.ClientId = "laoliu";
            tokenRequest.ClientSecret = "laoliu123456";
            tokenRequest.Scope = "TestApi";
            tokenRequest.UserName = "admin";
            tokenRequest.Password = "password";


            var tokenResponse = await client.RequestPasswordTokenAsync(tokenRequest);

            var token = tokenResponse.AccessToken;
            var tokenType = tokenResponse.TokenType;

            _token = $"{tokenType} {token}";

            return _token;
        }
    }
    public static class GrpcClient
    {
        /// <summary>
        /// rpc 工厂注入
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddWPFGrpc(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            services.AddGrpcClient<FieldRpc.FieldRpcClient>(options =>
            {
                options.Address = new Uri("https://localhost:7188");
            }).AddCallCredentials(async (context, metadata) =>
            {
                var token = await WpfAuthClient.GetToken();
                metadata.Add("Authorization", token);
            });

            return services;
        }
    }

三、执行效果展示

        1)启动鉴权中心

         2) 启动gRPC后端服务

        3)先看下不传token的结果

         4)加入token获取传递展示

授权中心返回

 gRPC服务展示

 客户端返回成功

 四、源码地址

链接:https://pan.baidu.com/s/1viu-REcR-ySdR0FE05sohg 
提取码:y0m4


http://www.niftyadmin.cn/n/4951766.html

相关文章

Gradio入门到进阶全网最详细教程:快速搭建AI算法可视化部署演示(侧重项目搭建和案例分享)

常用的两款AI可视化交互应用比较&#xff1a; Gradio Gradio的优势在于易用性&#xff0c;代码结构相比Streamlit简单&#xff0c;只需简单定义输入和输出接口即可快速构建简单的交互页面&#xff0c;更轻松部署模型。适合场景相对简单&#xff0c;想要快速部署应用的开发者。便…

查看 Linux 内核版本的几种方法

uname -a uname -srm uname -r 分拆&#xff1a;Linux 5.13.0-19-generic x86 64 5-内核版本 13-主修订版本 0-19 -次要修订版本 过查看 /proc/version 文件确认 /proc 目录包含虚拟文件&#xff0c;其中包含有关系统内存&#xff0c;CPU内核&#xff0c;已安装文件系统等的信…

科兴未来|淄博高新区第三届高层次人才创赛报名中!

淄博高新区举办第三届“天淄雄厚博揽英才”高层次人才创新创业大赛&#xff0c;旨在以本次大赛为契机&#xff0c;结合新能源制造、智能微系统、大健康、新材料、金融科技“41”主导产业&#xff0c;汇聚一批海内外原创性、引领性的高科技创新创业项目&#xff0c;增强创新活力…

基于Helm管理Kubernetes应用

Kubernetes部署方式 官方提供Kubernetes部署3种方式 minikube Minikube是一个工具&#xff0c;可以在本地快速运行一个单点的Kubernetes&#xff0c;尝试Kubernetes或日常开发的用户使用。不能用于生产环境。 官方文档&#xff1a;Install Tools | Kubernetes 二进制包 从…

antd5源码调试环境搭建(window系统)

将antd源码克隆至本地 $ git clone gitgithub.com:ant-design/ant-design.git $ cd ant-design $ npm install $ npm start前提安装python3、安装node版本18版本 不然后续安装依赖会报python3相关的错误。 项目需要使用git 初始化 不然会报husky相关的错误 git init重新安…

C++ 对象生成:构造函数

对象生成&#xff1a;构造函数 一、构造函数特性二、三种构造函数1.无参构造函数2.有参构造函数3.拷贝构造函数 一、构造函数特性 C编译器提供了构造函数供程序生成对象这是一个与类同名的函数&#xff0c;参数可以有多种形式&#xff08;重载&#xff09;没有返回类型声明一般…

设置Windows主机的浏览器为wls2的默认浏览器

1. 准备工作 wsl是可以使用Windows主机上安装的exe程序&#xff0c;出于安全考虑&#xff0c;默认情况下改功能是无法使用。要使用的话&#xff0c;终端需要以管理员权限启动。 我这里以Windows Terminal为例&#xff0c;介绍如何默认使用管理员权限打开终端&#xff0c;具体…

DeepSort:基于检测的目标跟踪的经典

本文来自公众号“AI大道理” DeepSORT在SORT的基础上引入了深度学习的特征表示和更强大的目标关联方式&#xff0c;有效地减少了身份切换的数量&#xff0c;缓解了重识别问题。 ​ 1、DeepSORT简介 DeepSORT的主要思想是将目标检测和目标跟踪两个任务相结合。 首先使用目标检…