.netcore grpc身份验证和授权

这篇具有很好参考价值的文章主要介绍了.netcore grpc身份验证和授权。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、鉴权和授权(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)启动鉴权中心

.netcore grpc身份验证和授权,.netcore上的GRPC详解,.netcore,rpc

         2) 启动gRPC后端服务

.netcore grpc身份验证和授权,.netcore上的GRPC详解,.netcore,rpc

        3)先看下不传token的结果

.netcore grpc身份验证和授权,.netcore上的GRPC详解,.netcore,rpc

         4)加入token获取传递展示

授权中心返回

.netcore grpc身份验证和授权,.netcore上的GRPC详解,.netcore,rpc

 gRPC服务展示

.netcore grpc身份验证和授权,.netcore上的GRPC详解,.netcore,rpc

 客户端返回成功

.netcore grpc身份验证和授权,.netcore上的GRPC详解,.netcore,rpc

 四、源码地址

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

下一篇https://blog.csdn.net/qq_31975127/article/details/132446555文章来源地址https://www.toymoban.com/news/detail-664126.html

到了这里,关于.netcore grpc身份验证和授权的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • .netcore grpc客户端工厂及依赖注入使用

    gRPC 与  HttpClientFactory  的集成提供了一种创建 gRPC 客户端的集中方式。 可以通过依赖包Grpc.Net.ClientFactory中的AddGrpcClient进行gRPC客户端依赖注入 AddGrpcClient函数提供了许多配置项用于处理一些其他事项;例如AOP、重试策略等 创建一个WPF客户端 在App.xaml.cs代码类里重写OnStartup方

    2024年02月12日
    浏览(22)
  • .NetCore gRpc 客户端与服务端的单工通信Demo

    方式一 使用vs 2022(也可以是其他版本)创建一个grpc的服务,如下这样 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uipEG9Xu-1687172462785)(C:UsersAdministratorAppDataRoamingTyporatypora-user-imagesimage-20230619183828284.png)] 简单方便,创建项目后的目录结构如下图

    2024年02月09日
    浏览(42)
  • 掌握 gRPC 和 RPC 的关键区别

    1、RPC 的本质 首先,我们探讨一下什么是  RPC 。RPC,缩写为 Remote Procedure Call Protocol,直译来看就是 远程过程调用协议 。 讲得通俗一些: RPC 是一种 通信机制 RPC 实现了 客户端/服务器 通信模型 官方的定义可能会这样解释: 它是一种协议,可以使程序能在网络上请求远程计

    2024年02月02日
    浏览(23)
  • nodejs微服务:RPC与GRPC框架

    RPC RPC(Remote Procedure Call Protocol),是远程过程调用的缩写 通俗的说就是调用远处的一个函数,与之相对应的是本地函数调用 本地函数调用:参数,返回值,代码段都在本地的一个进程空间内 远程函数调用:远程,即跨进程,这个进程部署在另一台服务器上,也就是调用另一台

    2023年04月20日
    浏览(28)
  • 【gRPC】第1篇 全面讲解RPC原理(必收藏)

    目录 1、什么是 RPC  2、为什么要用 RPC  3、常用的 RPC 框架 4、RPC 的调用流程 RPC(Remote Procedure Call Protocol)远程过程调用协议 ,目标就是让远程服务调用更加简单、透明。 RPC 框架负责屏蔽底层的传输方式(TCP 或者 UDP)、序列化方式(XML/Json/ 二进制)和通信细节,服务调用

    2023年04月09日
    浏览(23)
  • rpc、gRPC快速入门,python调用,protobuf协议

    远程过程调用协议RPC (Remote Procedure Call Protocol) RPC是指远程过程调用,也就是说两台服务器A,B,一个应用部署在A服务器上,想要调用B服务器上应用提供的函数/方法,由于不在一个内存空间,不能直接调用,需要通过网络来表达调用的语义和传达调用的数据 举例:在 a服务内

    2024年02月13日
    浏览(44)
  • 【C++】开源:grpc远程过程调用(RPC)配置与使用

    😏 ★,° :.☆( ̄▽ ̄)/$: .°★ 😏 这篇文章主要介绍grpc远程过程调用(RPC)配置与使用。 无专精则不能成,无涉猎则不能通。。——梁启超 欢迎来到我的博客,一起学习,共同进步。 喜欢的朋友可以关注一下,下次更新不迷路🥞 项目Github地址: https://github.com/grpc/grpc 官网

    2024年02月15日
    浏览(35)
  • 深入剖析gRPC:Google开源的高性能RPC框架

    在本篇文章中,我们将深入剖析gRPC,Google开源的高性能RPC框架。gRPC是一种基于HTTP/2的高性能、可扩展的RPC框架,它使用Protocol Buffers作为接口定义语言,可以在多种编程语言之间实现无缝通信。 gRPC的核心设计理念是:通过使用HTTP/2作为传输协议,实现高效、可扩展的RPC通信

    2024年02月19日
    浏览(38)
  • go-zero/grpc的rpc服务间传递额外数据

    go-zero/grpc的rpc服务间传递额外数据 2024/02/18 客户端: 初始化 md 也可如下方式: 追加新的如下: 也可使用 md 的 Set 和 Append 方法追加: 服务端: 注意 key 都会被转为小写,即使客户端为大写: 而且 key 只能由 数字、字母和三个特殊字符“-_.”组成,大写字母会自动被转为小写

    2024年02月19日
    浏览(50)
  • gRPC---自定义Token验证

    我们先看一个gRPC提供我们的一个接口,这个接口中有两个方法,接口位于credentials包下,这个接口需要客户端来实现 第一个方法作用是获取元数组信息,也就是客户端提供的key,value对,context用于控制超时和取消,uri是请求入口处的uri, 第二个方法的作用是否需要基于TLS认

    2024年02月01日
    浏览(18)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包