gRPC是什么
gRPC是可以在任何环境中运行的现代开源高性能RPC框架。它可以通过可插拔的支持来有效地连接数据中心内和跨数据中心的服务,以实现负载平衡,跟踪,运行状况检查和身份验证。它也适用于分布式计算的最后一英里,以将设备,移动应用程序和浏览器连接到后端服务。

proto文件
用于定义gRPC服务和消息的协定;服务端和客户端共享proto文件。

使用新模板创建gRPC服务端
.NETcore 3.0创建项目提供了一个新的gRPC模板,可以轻松地使用ASP.NET Core构建gRPC服务。我们按照步骤一步一步创建AA.GrpcService 服务,当然你可以使用命令:dotnet new grpc -o GrpcGreeter

选择gRPC服务项目模板

最终生成的项目

  1. syntax = "proto3";
  2.  
  3. option csharp_namespace = "AA.GrpcService";
  4.  
  5. package Greet;
  6.  
  7. // The greeting service definition.
  8. service Greeter {
  9. // Sends a greeting
  10. rpc SayHello (HelloRequest) returns (HelloReply);
  11. }
  12.  
  13. // The request message containing the user's name.
  14. message HelloRequest {
  15. string name = ;
  16. }
  17.  
  18. // The response message containing the greetings.
  19. message HelloReply {
  20. string message = ;
  21. }

GreeterService.cs

  1. public class GreeterService : Greeter.GreeterBase
  2. {
  3. private readonly ILogger<GreeterService> _logger;
  4. public GreeterService(ILogger<GreeterService> logger)
  5. {
  6. _logger = logger;
  7. }
  8.  
  9. public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
  10. {
  11. return Task.FromResult(new HelloReply
  12. {
  13. Message = "Hello " + request.Name
  14. });
  15. }
  16. }

Startup.cs

  1. public class Startup
  2. {
  3. // This method gets called by the runtime. Use this method to add services to the container.
  4. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  5. public void ConfigureServices(IServiceCollection services)
  6. {
  7. services.AddGrpc();
  8. }
  9. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  10. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  11. {
  12. if (env.IsDevelopment())
  13. {
  14. app.UseDeveloperExceptionPage();
  15. }
  16. app.UseRouting();
  17. app.UseEndpoints(endpoints =>
  18. {
  19. endpoints.MapGrpcService<GreeterService>();
  20. endpoints.MapGet("/", async context =>
  21. {
  22. await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
  23. });
  24. });
  25. }
  26. }

创建完成之后,自动包含了包的引用、proto文件的创建、services服务的生成,模板项目在后台执行一些操作如

创建一个包含所有gRPC依赖项的ASP.NET Core项目。
创建一个名为的gRPC服务定义文件greet.proto。
根据服务定义文件自动生成所有gRPC存根。
GreeterService.cs根据自动生成的gRPC存根创建gRPC服务。
在Startup.cs中配置gRPC管道映射到GreeterService.cs
运行服务

创建gRPC客户端
下面,我们创建一个控制台应用程序作为客户端调用gRPC服务;

引用gRPC服务,步骤:右键项目添加=》服务引用弹出以下页面;

点击确定

我们看项目结构,他们会自动帮我们处理一下操作:

添加引用包:
 package Grpc.Net.ClientFactory
 package Google.Protobuf
 package Grpc.Tools
Protos 文件(包含greet.proto)自动从AA.GrpcService项目拷贝
自动添加节点

  1. <ItemGroup>
  2.   <Protobuf Include="..\AA.GrpcService\Protos\greet.proto" GrpcServices="Client">
  3.     <Link>Protos\greet.proto</Link>
  4.   </Protobuf>
  5. </ItemGroup>

最后,添加以下代码进行gRPC请求;

  1. static async System.Threading.Tasks.Task Main(string[] args)
  2. {
  3. var httpClientHandler = new HttpClientHandler();
  4. httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
  5. var httpClient = new HttpClient(httpClientHandler);
  6.  
  7. using var channel = GrpcChannel.ForAddress("https://localhost:5002", new GrpcChannelOptions { HttpClient = httpClient });
  8. var client = new Greeter.GreeterClient(channel);
  9. var response = await client.SayHelloAsync(new HelloRequest { Name = "gRPC" });
  10. Console.WriteLine("Greeting:" + response.Message);
  11. Console.WriteLine("Press a key to exit");
  12. Console.ReadKey();
  13. }

运行结果图:

gRPC与IdentityServer4集成认证授权
Ids4.Server

1.创建一个.net core的webapi

2.nuget引用最新的IdentityServer4的包

<PackageReference Include="IdentityServer4" Version="3.0.1" />
IdentityServer4相关配置,因为是演示所以很简单,生产场景大家根据实际情况配置。

  1. namespace Ids4.Server
  2. {
  3. public class Config
  4. {
  5. public static IEnumerable<IdentityResource> GetIdentityResources()
  6. {
  7. return new List<IdentityResource>
  8. {
  9. new IdentityResources.OpenId(),
  10. new IdentityResources.Profile(),
  11. new IdentityResources.Email(),
  12. };
  13. }
  14. public static IEnumerable<ApiResource> GetApis()
  15. {
  16. return new List<ApiResource>
  17. {
  18. new ApiResource("api", "Demo API")
  19. {
  20. ApiSecrets = { new Secret("secret".Sha256()) }
  21. }
  22. };
  23. }
  24. public static IEnumerable<Client> GetClients()
  25. {
  26. return new List<Client>
  27. {
  28. new Client
  29. {
  30. ClientId = "client",
  31. ClientSecrets = { new Secret("secret".Sha256()) },
  32.  
  33. AllowedGrantTypes = GrantTypes.ClientCredentials,
  34. AllowedScopes = { "api" },
  35. },
  36. };
  37. }
  38. }
  39. }

4. startup.cs 注入服务

  1. services.AddIdentityServer().AddInMemoryApiResources(Config.GetApis())
  2. .AddInMemoryIdentityResources(Config.GetIdentityResources())
  3. .AddInMemoryClients(Config.GetClients())
  4. .AddDeveloperSigningCredential(persistKey: false);

5. startup.cs 配置http请求管道

  1. app.UseIdentityServer();

6. 启动服务,使用PostMan进行调试,有返回结果表示服务创建成功

  1. POST /connect/token HTTP/1.1
  2. Host: localhost:
  3. Content-Type: application/x-www-form-urlencoded
  4. grant_type=client_credentials&client_id=client&client_secret=secret

  1. {
  2. "access_token":"eyJhbGciOiJSUzI1NiIsImtpZCI6IlVYODJRTk9LMWRMR1dDREVUd0xQbkEiLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE1NzE4MDU4MzAsImV4cCI6MTU3MTgwOTQzMCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjoiYXBpIiwiY2xpZW50X2lkIjoiY2xpZW50Iiwic2NvcGUiOlsiYXBpIl19.DgJJqIOOSICEGa7S5R4Ok7Pp4hxPjGQP12T4LsDHD5tRsYiV58VcvooglVehKmMbydE7yA7JnYqBR--2Gbss9zjYyq41iY2lP-Y79v70jlVn9TvrpWOIljnWOvLApjFMEXJuV4VHwcXQ7ssgXFrY4Mg_QPaxkJRIKAI8T5cP2W1KvOBkaZqx45o8VpQBfpEyoRjPHQW0wPrM6bBU4IxfTosy874pn2NXVhe2DaPeAcReXYsz5AVtJ4Vt-4fVS1JtcA-aj6OQ__RWYqNK_ApQRFZsuyJKG27EBBrc0byrpw_G1PReRl8hlYnXidGFvijGEawlyEAANXzNNXDk7cSJ2A",
  3. "expires_in":,
  4. "token_type":"Bearer",
  5. "scope":"api"
  6. }

改造Grpc.Server支持IdentityServer4

1. 引入nuget包

<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
2. startup.cs 注入服务,和IdentityServer4一样。

  1. services.AddGrpc(x => x.EnableDetailedErrors = false);
  2. services.AddAuthorization();
  3. services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
  4. .AddIdentityServerAuthentication(options =>
  5. {
  6. options.Authority = "http://localhost:5000";
  7. options.RequireHttpsMetadata = false;
  8. });

3. startup.cs 配置http请求管道

  1. if (env.IsDevelopment())
  2. {
  3. app.UseDeveloperExceptionPage();
  4. }
  5. app.UseRouting();
  6. app.UseAuthentication();
  7. app.UseAuthorization();
  8. app.UseEndpoints(endpoints =>
  9. {
  10. endpoints.MapGrpcService<GreeterService>();
  11.  
  12. endpoints.MapGet("/", async context =>
  13. {
  14. await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
  15. });
  16. });

4. 对需要授权的服务打标签[Authorize],可以打在类上也可以打在方法上

  1. [Authorize]
  2. public class GreeterService : Greeter.GreeterBase
  3. {
  4. }

这个时候我们启动Grpc.Client访问Grpc.Server服务

发现报错401。说明此服务需要携带令牌才能访问。

改造Grpc.Client携带令牌访问(需要添加IdentityServer4引用)

  1. static async System.Threading.Tasks.Task Main(string[] args)
  2. {
  3. var httpClientHandler = new HttpClientHandler();
  4. httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
  5. var httpClient = new HttpClient(httpClientHandler);
  6.  
  7. //获取token可以直接使用HttpClient来获取,这里使用IdentityModel来获取token
  8. var disco = await httpClient.GetDiscoveryDocumentAsync("http://localhost:5000");
  9. if (!disco.IsError)
  10. {
  11. var token = await httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest()
  12. {
  13. Address = disco.TokenEndpoint,
  14. ClientId = "client",
  15. ClientSecret = "secret"
  16. });
  17. var tokenValue = "Bearer " + token.AccessToken;
  18. var metadata = new Metadata
  19. {
  20. { "Authorization", tokenValue }
  21. };
  22. var callOptions = new CallOptions(metadata);
  23. ////
  24. using var channel = GrpcChannel.ForAddress("https://localhost:5002", new GrpcChannelOptions { HttpClient = httpClient });
  25. var client = new Greeter.GreeterClient(channel);
  26. var response = await client.SayHelloAsync(new HelloRequest { Name = "gRPC" },callOptions);
  27. Console.WriteLine("Greeting:" + response.Message);
  28. }
  29.  
  30. Console.WriteLine("Press a key to exit");
  31. Console.ReadKey();
  32. }

小结: .NETcore 3.0 使得使用gRPC是非常方便集成到项目中,希望这篇文章使你可以了解.NETcore与gRPC结合使用。那gRPC适用于以下场景

微服务– gRPC专为低延迟和高吞吐量通信而设计。 gRPC对于效率至关重要的轻量级微服务非常有用。

点对点实时通信– gRPC对双向流具有出色的支持。 gRPC服务可以实时推送消息而无需轮询。

多种语言环境– gRPC工具支持所有流行的开发语言,因此gRPC是多语言环境的理想选择。

网络受限的环境– gRPC消息使用轻量级消息格式Protobuf进行了序列化。 gRPC消息始终小于等效的JSON消息。

参考:

https://docs.microsoft.com/en-us/aspnet/core/grpc/troubleshoot?view=aspnetcore-3.0

https://docs.microsoft.com/zh-cn/aspnet/core/grpc/?view=aspnetcore-3.0
https://www.grpc.io/
https://developers.google.com/protocol-buffers/docs/proto3
https://www.cnblogs.com/stulzq/p/11581967.html

.Net Core3.0使用gRPC 和IdentityServer4的更多相关文章

  1. .Net Core3.0使用gRPC

    gRPC是什么 gRPC是可以在任何环境中运行的现代开源高性能RPC框架.它可以通过可插拔的支持来有效地连接数据中心内和跨数据中心的服务,以实现负载平衡,跟踪,运行状况检查和身份验证.它也适用于分布式 ...

  2. .net core gRPC与IdentityServer4集成认证授权

    前言 随着.net core3.0的正式发布,gRPC服务被集成到了VS2019.本文主要演示如何对gRPC的服务进行认证授权. 分析 目前.net core使用最广的认证授权组件是基于OAuth2. ...

  3. What?VS2019创建新项目居然没有.NET Core3.0的模板?Bug?

    今天是个值得欢喜的日子,因为VS2019在今天正式发布了.作为微软粉,我已经用了一段时间的VS2019 RC版本了.但是,今天有很多小伙伴在我的<ASP.NET Core 3.0 上的gRPC服 ...

  4. .Net Core 3.0使用Grpc进行远程过程调用

    因为.Net Core3.0已经把Grpc作为一等臣民了,作为爱好新技术的我,当然要尝鲜体验一下了,当然感觉是Grpc作为跨语言的产品做的相当好喽,比起Dubbo这种的,优势和劣势还是比较明显的. 我 ...

  5. 2019年第一天——使用Visual Studio 2019 Preview创建第一个ASP.Net Core3.0的App

    一.前言: 全文翻译自:https://www.talkingdotnet.com/creating-first-asp-net-core-3-0-app-visual-studio-2019/ Vi ...

  6. VS2019没有.net core3.0模板的解决办法

    今天装好了,net core sdk 3.0之后,打开Visual Studio2019后,新建项目时发现尽然没有.net core3.0的模板. 搜了下其他博主的文章,按照文章里做了如下设置:   ...

  7. ASP.NET Core 3.0 使用gRPC

    一.简介 gRPC 是一个由Google开源的,跨语言的,高性能的远程过程调用(RPC)框架. gRPC使客户端和服务端应用程序可以透明地进行通信,并简化了连接系统的构建.它使用HTTP/2作为通信协 ...

  8. asp.net core3.0 mvc 用 autofac

    好久没有写文章了,最近在用.net core3.0,一些开发中问题顺便记录: 1.首先nuget引入 Autofac Autofac.Extensions.DependencyInjection 2. ...

  9. 使用.net core3.0 正式版创建Winform程序

    前阵子一直期待.net core3.0正式版本的出来,以为这个版本出来,Winform程序又迎来一次新生了,不过9.23日出来的马上下载更新VS,创建新的.net core Winform项目,发现并 ...

随机推荐

  1. Mac OS中的”任务管理器“

    在开发使用过程中,经常需要通过任务管理器来查看进程的一些情况以及杀掉一些进程,Mac中也有类似于Windows的”资源管理器“. 启动台->其他 找到”活动监视器“ 活动监视器即是”任务管理器“ ...

  2. ios证书制作与上架指南

    项目开发完了,要上架 ios AppStore 记录一下经过,以及需要提前准备和预防的东西,以便下次省心! 一.首先要申请开发者账号: 账号按流程注册申请,当时申请了够10遍,总结以下经验: 1.申请 ...

  3. WorkFlow四:添加用户决策步骤

    沿用之前的例子,做个用户决策步骤. 1.事物代码SWDD: 进入抬头,点击类的绑定按钮. 2.选择类的绑定,点击继续. 这是类的绑定已经变色了.这时候点击保存,再点击返回到图片逻辑流界面. 3.在发送 ...

  4. Colorimetry

    [Colorimetry] 1.Example of Spectral Power Distribution Application An example of the spectral power ...

  5. python测试开发django-71.自定义标签tag

    前言 django的模板里面有很多标签可以快速实现一些功能,比如{% url url_name%} 可以快捷的导入一个本地url地址. 上一篇我们可以自定义一些过滤器https://www.cnblo ...

  6. SpringBoot中使用Maven插件,上传docker镜像

    开启docker远程端口 我上一篇里面写了,这里暴露的路径: 18.16.202.95:2375 简单构建 配置pom.xml文件 在properties中增加一行指定远程主机的位置 <prop ...

  7. Vyos的基本配置

    修改用户密码 Enter configuration mode configure Set password set system login user [username] authenticati ...

  8. Debian 安装 yum

    sudo apt-get updatesudo apt-get install build-essentialsudo apt-get install yum

  9. About Her

    突然想给黑寡妇写点儿东西......(也许很多都不是我写的,但是能表达我的心意) 1. 众人进量子领域前最后一句话是她笑着说"一分钟后见." 而最终没有回来的,只有她自己一个 2. ...

  10. 获取当前页面url指定参数值

    function getParam(paramName) { paramValue = "", isFound = !1; if (this.location.search.ind ...