安阳网站建设首选,网站开发需要多少钱新闻,免费个人网站建站申请一下,保定网站建设的过程点击上方蓝字小黑在哪里关注我吧前言IdentityServer4 是为ASP.NET Core系列量身打造的一款基于 OpenID Connect 和 OAuth 2.0 认证的框架IdentityServer4官方文档#xff1a;https://identityserver4.readthedocs.io/看这篇文章前默认你对IdentityServer4 已经有一… 点击上方蓝字小黑在哪里关注我吧前言IdentityServer4 是为ASP.NET Core系列量身打造的一款基于 OpenID Connect 和 OAuth 2.0 认证的框架IdentityServer4官方文档https://identityserver4.readthedocs.io/看这篇文章前默认你对IdentityServer4 已经有一些了解。本篇使用IdentityServer4的4.x版本跟老版本的稍微有些差别。下面直接进入正题。鉴权中心 创建IdentityServer4项目 使用IdentityServer4 来搭建一个鉴权中心首先建议安装一下IdentityServer4的官方项目模板。也可以不安装自己创建项目然后NuGet安装需要的包也行。不过还是推荐用官方的模板很方便。命令行执行dotnet new -i IdentityServer4.Templatesimage-20200629205619088安装完成后会多出以下项目模板image-20200629205731577我这里选用is4inmem这个模板来创建项目这个模板的数据都是写死在内存中的并且包含了Quickstart页面比较简单方便。来到我的项目目录下执行dotnet new is4inmem --name Idpimage-20200701190325246执行完成会生成以下文件image-20200701195853822VS2019打开项目image-20200701195955107运行项目image-20200701200225015 配置ApiResource、ApiScope、Clients 修改Startup// in-memory, code config
builder.AddInMemoryIdentityResources(Config.IdentityResources);
builder.AddInMemoryApiScopes(Config.ApiScopes);
//添加API资源
builder.AddInMemoryApiResources(Config.ApiResources);
builder.AddInMemoryClients(Config.Clients);这里比之前版本多了一个添加ApiScopes的方法builder.AddInMemoryApiScopes(Config.ApiScopes);因为我接下来有要保护的API资源所以需要添加一行builder.AddInMemoryApiResources(Config.ApiResources);Config中的代码public static class Config
{public static IEnumerableIdentityResource IdentityResources new IdentityResource[]{new IdentityResources.OpenId(),new IdentityResources.Profile(),};public static IEnumerableApiScope ApiScopes new ApiScope[]{new ApiScope(scope1),//new ApiScope(scope2),};public static IEnumerableApiResource ApiResources new ApiResource[]{new ApiResource(api1,#api1){//!!!重要Scopes { scope1}},//new ApiResource(api2,#api2)//{// //!!!重要// Scopes { scope2}//},};public static IEnumerableClient Clients new Client[]{new Client{ClientId postman client,ClientName Client Credentials Client,AllowedGrantTypes GrantTypes.ClientCredentials,ClientSecrets { new Secret(postman secret.Sha256()) },AllowedScopes { scope1 }},};
}
我添加了一个ID为postman client的客户端授权模式就用最简单的ClientCredentials客户端模式。需要注意的是4.x版本的ApiScope和ApiResource是分开配置的然后在ApiResource中一定要添加Scopes。如果你在网上搜的IdentityServer4教程比较老的都是没有这个ApiScope的默认ApiResource的Name作为Scope。类似这样public static IEnumerableApiResource ApiResources new ApiResource[]{new ApiResource(api1,#api1),//错误new ApiResource(api2,#api2),//错误};public static IEnumerableClient Clients new Client[]{new Client{......AllowedScopes { api1, api2 }},};
如果你这么写的话虽然不影响你获取token但是你访问api资源的话永远会得到一个401错误ApiResource下面添加一个api1资源新建asp.netcore web应用并使用webapi模板image-20200701211036365NuGet安装Microsoft.AspNetCore.Authentication.JwtBearerStartup部分代码public void ConfigureServices(IServiceCollection services)
{services.AddControllers();services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options {//IdentityServer地址options.Authority http://localhost:5001;//对应Idp中ApiResource的Nameoptions.Audience api1;//不使用httpsoptions.RequireHttpsMetadata false;});
}// 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.UseHttpsRedirection();app.UseRouting();//身份验证app.UseAuthentication();//授权app.UseAuthorization();app.UseEndpoints(endpoints {endpoints.MapControllers();});
}
给WeatherForecastController添加[Authorize]标记image-20200701214601854运行Api1Resource用postman测试访问weatherforecast接口image-20200701214742071此时得到401错误。下面先去Idp获取一个tokenimage-20200701215031535拿到token后再去访问weatherforecast就没问题了image-20200701215748634进行到这里好像跟scope都没什么关系那么scope到底有什么用处呢ApiScope策略授权继续修改代码。Api1Resource项目NuGet安装IdentityServer4.AccessTokenValidationimage-20200701221017612再新建一个TestController用于区分image-20200701223359517下面我需要做的是使用scope结合策略授权来分别限制TestController和WeatherForecastController的访问权限。修改Startuppublic void ConfigureServices(IServiceCollection services)
{......services.AddAuthorization(options {//基于策略授权options.AddPolicy(WeatherPolicy, builder {//客户端Scope中包含api1.weather.scope才能访问builder.RequireScope(api1.weather.scope);});//基于策略授权options.AddPolicy(TestPolicy, builder {//客户端Scope中包含api1.test.scope才能访问builder.RequireScope(api1.test.scope);});});
}
为了好理解我把scope名称分别改成了api1.weather.scope和api1.test.scope。WeatherForecastController的Authorize标记修改一下[Authorize(Policy WeatherPolicy)]TestController的代码很简单image-20200701224046637因为修改了scope名称需要把Idp中的scope名称也改一下public static IEnumerableApiScope ApiScopes new ApiScope[]{new ApiScope(api1.weather.scope),new ApiScope(api1.test.scope),//new ApiScope(scope2),};public static IEnumerableApiResource ApiResources new ApiResource[]{new ApiResource(api1,#api1){//!!!重要Scopes { api1.weather.scope, api1.test.scope }},//new ApiResource(api2,#api2)//{// //!!!重要// Scopes { scope2}//},};
客户端定义AllowedScopes暂时只给一个api1.weather.scope测试一下public static IEnumerableClient Clients new Client[]{new Client{ClientId postman client,ClientName Client Credentials Client,AllowedGrantTypes GrantTypes.ClientCredentials,ClientSecrets { new Secret(postman secret.Sha256()) },AllowedScopes { api1.weather.scope }},};
postman获取tokenimage-20200701225242813访问weatherforecast接口正常响应200。image-20200701225430395再访问test得到403错误image-20200701225508071接下来修改一下Idp的客户端定义添加api1.test.scopeAllowedScopes { api1.weather.scope, api1.test.scope }修改Idp后一定要重新获取tokenjwt就是这样一旦生成就无法改变。image-20200701230022811拿到新的token后访问test和weatherforecast这时候就都可以正常响应了。image-20200701230107290image-20200701230209695总结以上使用IdentityServer4搭建了一个鉴权中心保护API资源并使用ApiScope配合策略授权完成了一个简单的权限控制。IdentityServer4的玩法非常多知识点也很多。强烈推荐B站的solenovex 杨老师的视频地址https://www.bilibili.com/video/BV16b411k7yM 多看几遍会有收获。。。需要代码的点这里https://github.com/xiajingren/IdentityServer4-4.x-Scope-Demo- END -如果本文对您有用不妨点个“在看”或者转发朋友圈支持一下