Server端

StartUp类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; namespace GRPCTokenServer
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
//services.AddHttpContextAccessor(); services.AddGrpc(options => { options.EnableDetailedErrors = true; });
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:54311/";
options.RequireHttpsMetadata = false; options.ApiName = "identity";
options.SaveToken = true;
});
services
.AddControllers();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting(); app.UseAuthentication();
app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
// 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
endpoints.MapGrpcService<GreeterService>();
//endpoints.MapControllers();
});
}
}
}

Service

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Grpc.Core;
using Microsoft.AspNetCore.Authorization; namespace GRPCTokenServer
{
[Authorize(AuthenticationSchemes = "Bearer")]
public class GreeterService : Greeter.GreeterBase
{
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
var user = context.GetHttpContext().User;
return Task.FromResult(new HelloReply
{
Message = "Hello " + request.Name
});
}
}
}

proto

syntax = "proto3";

option csharp_namespace = "GRPCTokenServer";

package Greet;

// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
} // The request message containing the user's name.
message HelloRequest {
string name = ;
} // The response message containing the greetings.
message HelloReply {
string message = ;
}

Client

using Grpc.Core;
using Grpc.Net.Client;
using GRPCTokenServer;
using System;
using System.Net.Http; namespace GRPCTokenClient
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
// AppContext.SetSwitch(
//"System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport",
//true);
// var httpClient = new HttpClient();
// // The port number(50051) must match the port of the gRPC server.
// httpClient.BaseAddress = new Uri("http://localhost:50051");
// var client = GrpcClient.Create<Greeter.GreeterClient>(httpClient); // HttpClient httpClient = new HttpClient();
//httpClient.BaseAddress = new Uri("https://localhost:50051");
//var result = await httpClient.PostAsync("api/token", new { Email = "admin@contract.com", Password = "12345678" }.AsJson());
var tokenValue = "Bearer " + "eyJhbGciOiJSUzI1NiIsImtpZCI6Ijk4OTIzRkRERTkxODJDOURERjRGQzZCQzNBMEI1RDUzNDNFNkM4QjEiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJtSklfM2VrWUxKM2ZUOGE4T2d0ZFUwUG15TEUifQ.eyJuYmYiOjE1NjEyNjEwODUsImV4cCI6MTU2MjI2MTA4NSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1NDMxMSIsImF1ZCI6ImlkZW50aXR5IiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZWlkZW50aWZpZXIiOiI0NzczYzUzMi0wMDg1LTQwZGUtYTllNy1iZTNlMjBhNjdlOTQiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiMTU5MDE0MDIzODIiLCJBc3BOZXQuSWRlbnRpdHkuU2VjdXJpdHlTdGFtcCI6Iks0RlE2Sk1TNEZPUzROR1Q2TE9UVFlJR1ZDRTZRQlRVIiwidXNlcmlkIjoiNDc3M2M1MzItMDA4NS00MGRlLWE5ZTctYmUzZTIwYTY3ZTk0IiwidXNlcm5hbWUiOiIxNTkwMTQwMjM4MiJ9.pSEkPwyRMNeDYd6ONR0xjJMfhFhOgZB_gcr0fa7NP8dAnPfuf4aW0xIzNsAp6NGn91fu9vbV5gSEbTUghRfzKemEcPwIDaeho1oYvV-xFRWBBo4JFBx5FcB-kVdy4TeFCTu1nTIb0MUqmkgk40HFngmK7jW9epAu2m1YYvyvweqoe5cS4eHcEMun4lSOlJwoCmL-V1DW_LQb8LojrBUjn2mz3f0yAlUWIA_vi_Z37QX60Sg-BMtlrH0fdaJuypNdRtlWp6qvNEZgZ496wIjHnSCUr15Z6AbqQfa2XTBI16pLj96HTeTjkxGR0XmoCaRmXWiTeOg0nFq5pZ8dDoJOIg"; var metadata = new Metadata
{
{ "Authorization", tokenValue }
};
CallOptions callOptions = new CallOptions(metadata); var channel = new Channel("localhost:50051", SslCredentials.Insecure); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync(
new HelloRequest { Name = "GreeterClient" }, callOptions);
Console.WriteLine("Greeting: " + reply.Message);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}

https://github.com/cysnet/Secure_gRpc

https://github.com/cysnet/GRPC_IdentityServer4

https://damienbod.com/2019/03/06/security-experiments-with-grpc-and-asp-net-core-3-0/

GRPC Oauth IdentityServer4的更多相关文章

  1. .Net Core3.0使用gRPC 和IdentityServer4

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

  2. GRPC Oauth Identity

    gRPC中集成asp.net identity实现oAuth认证 在asp.net core 3.0中开启identity认证 asp.net core 3.0种需要导入的identity包与core ...

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

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

  4. IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习保护API

    IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习之保护API. 使用IdentityServer4 来实现使用客户端凭据保护ASP.N ...

  5. IdentityServer4 实现 OpenID Connect 和 OAuth 2.0

    关于 OAuth 2.0 的相关内容,点击查看:ASP.NET WebApi OWIN 实现 OAuth 2.0 OpenID 是一个去中心化的网上身份认证系统.对于支持 OpenID 的网站,用户不 ...

  6. IdentityServer4 实现 OAuth 2.0(密码模式 - HTTP Post 方式)

    之前写了一篇文章:<IdentityServer4 实现 OpenID Connect 和 OAuth 2.0> 上面这篇文章虽然详细,但都是点到为止的介绍,并没有实际应用的示例,所以,后 ...

  7. 【ASP.NET Core分布式项目实战】(一)IdentityServer4登录中心、oauth密码模式identity server4实现

    本博客根据http://video.jessetalk.cn/my/course/5视频整理 资料 OAuth2 流程:http://www.ruanyifeng.com/blog/2014/05/o ...

  8. 使用 IdentityServer4 实现 OAuth 2.0 与 OpenID Connect 服务

    IdentityServer4 是 ASP.NET Core 的一个包含 OIDC 和 OAuth 2.0 协议的框架.最近的关注点在 ABP 上,默认 ABP 也集成 IdentityServer4 ...

  9. 简单理解 OAuth 2.0 及资料收集,IdentityServer4 部分源码解析

    简单理解 OAuth 2.0 及资料收集,IdentityServer4 部分源码解析 虽然经常用 OAuth 2.0,但是原理却不曾了解,印象里觉得很简单,请求跳来跳去,今天看完相关介绍,就来捋一捋 ...

随机推荐

  1. 用WPF实现打印及打印预览

    原文:用WPF实现打印及打印预览 应该说,WPF极大地简化了我们的打印输出工作,想过去使用VC++做开发的时候,打印及预览可是一件极麻烦的事情,而现在我不会再使用C++来做Windows的桌面应用了- ...

  2. wpf 屏蔽热键

    原文:wpf 屏蔽热键 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/a771948524/article/details/9428923   us ...

  3. 专访黄勇:Java在未来的很长一段时间仍是主流(把老板当情人,把同事当小孩,把客户当病人)

    url:http://www.csdn.net/article/2015-09-06/2825621 2015-09-06 13:18 摘要:本文采访了现任阿里巴巴公司系统架构师黄勇,从事近十年的Ja ...

  4. cocos2d 滚动背景 举 无限

    void Bird::update(float time){ auto bg=this->getChildByTag(200); auto bg1=this->getChildByTag( ...

  5. 如何完全备份android在系统system分区和data分

    安德鲁斯系统备份是非常的情况下,可以使用.下面的这个python脚本.它可以用来备份整个data分:所有data分区的文件和文件夹打包data.zip.并产生recovery专用edify脚本upda ...

  6. sql count(1)不要和查询数据混用 非常耗时

    count(1)不要和查询数据混用 非常耗时 例子: SELECT w.[PKID], COUNT(1) OVER() AS TotalCount FROM w WITH(NOLOCK) INNER ...

  7. qt 透明度设置(setWindowOpacity 和 setAutoFillBackground 和 带透明度的画刷填充就好了)

    1,父窗口透明// 设置背景图片 QPalette pa;setAutoFillBackground(true);pa.setBrush(QPalette::Background,QBrush(QPi ...

  8. centos7 防火墙问题

    centos从7开始默认用的是firewalld,这个是基于iptables的,虽然有iptables的核心,但是iptables的服务是没安装的.所以你只要停止firewalld服务即可:sudo ...

  9. Win8 Metro(C#)数字图像处理--2.61哈哈镜效果

    原文:Win8 Metro(C#)数字图像处理--2.61哈哈镜效果  [函数名称] 哈哈镜效果函数  WriteableBitmap DistortingMirrorProcess(Writea ...

  10. 使用sklearn构建含有标量属性的决策树

    网络上使用sklearn生成决策树的资料很多,这里主要说明遇见标量数据的处理. 经查验参考资料,sklearn并非使用了课上以及书上讲的ID3算法,而是选择了CART,该算法生成二叉树:scikit- ...