网站制作网站建设项目规划书,做网站市场价格多少钱,建设网站成本,设计与绘制一个网站首页Oatuth2协议的客户端模式介绍Client Credentials Grant #xff08;客户端模式#xff09;是Oauth2.0协议中#xff0c;四种模式自建单的一种。它由两部分构成#xff0c;客户端和认证服务器。认证服务器确认客户端无误后返回一个token#xff0c;客户端请求带着token访问… Oatuth2协议的客户端模式介绍Client Credentials Grant 客户端模式是Oauth2.0协议中四种模式自建单的一种。它由两部分构成客户端和认证服务器。认证服务器确认客户端无误后返回一个token客户端请求带着token访问资源。一般使用场景是在一个安全的环境下例如我的同一个系统中一个api请求另外一个api。 这里借用下阮一峰老师画的图博客地址》http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.htmlIdentityServer4客户端模式实现首先我们创建一个core的api项目作为认证服务器添加nuget程序包IdentityServer4将启动端口设置为5000。接下来添加一个类取名字叫做Config我们用它来初始化Identityserver(配置要保护的资源和可以访问该API的客户端服务器)。代码如下:/// summary/// Idnetity配置初始化Identityserver/// /summarypublic class Config{//定义要保护的资源webapipublic static IEnumerableApiResource GetApiResources(){return new ListApiResource{new ApiResource(api1, My API)};}//定义可以访问该API的客户端public static IEnumerableClient GetClients(){return new ListClient{new Client(){ClientId client,AllowedGrantTypes GrantTypes.ClientCredentials, //设置模式客户端模式ClientSecrets {new Secret(secret.Sha256())},AllowedScopes { api1 }}};}}接下来配置startup将资源和客户端的初始信息服务加入到DI容器同时引用IdentityServer中间件。代码如下所示:public void ConfigureServices(IServiceCollection services){services.AddIdentityServer().AddDeveloperSigningCredential().AddInMemoryApiResources(Config.GetApiResources()) //配置资源.AddInMemoryClients(Config.GetClients()); //配置客户端services.AddMvc();}public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}//使用identityserver中间件app.UseIdentityServer();app.UseMvc();}再添加一个webapi项目作为我们的资源服务器。添加nuget包IdentityServer4.AccessTokenValidation将启动端口设置为5001。2、配置startup添加认证服务器地址和apiname 引用中间件代码如下:public void ConfigureServices(IServiceCollection services){services.AddAuthentication(Bearer).AddIdentityServerAuthentication(options {options.Authority http://localhost:5000; //配置Identityserver的授权地址options.RequireHttpsMetadata false; //不需要httpsoptions.ApiName api1; //api的name需要和config的名称相同});services.AddMvc();}public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseAuthentication();// 添加认证中间件app.UseMvc();}将受保护资源controller添加[Authorize]。因为资源服务器AddIdentityServerAuthentication 方法的参数和返回值都是AuthenticationBuilder类似于一个中间件所以可以多次调用AddIdentityServerAuthentication方法来控制这个api 资源可以让谁访问到。最开始我们直接访问资源服务器的api返回401因为我们的资源被保护了。这时候来到IdentityServer4的官网官网给出了这么一个地址》我们访问这个地址时候它会返回我们的Config配置》其中有一个token_endpoint的url地址我们带着Client的配置来访问它》此时拿到Token再带着token去访问我们的资源争取获取到资源数据》https://github.com/conanl5566/dotnet-core-Example/tree/master/WebApplication25