前言

建立Web Api项目

在同一个解决方案下建立一个Web Api项目IdentityServer4.WebApi,然后修改Web Api的launchSettings.json。参考第一节,当然可以不修改的,端口号为5001

{
"profiles": {
"IdentityServer4.WebApi": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"applicationUrl": "http://localhost:5001",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

添加Swagger帮助页面

官方文档:https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio&view=aspnetcore-3.1

Startup.ConfigureServices方法中将Swagger生成器添加到服务集合:

        public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(); // Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
}

OpenApiInfo需要 using Microsoft.OpenApi.Models;

在该Startup.Configure方法中,启用用于提供生成的JSON文档和Swagger UI的中间件:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
}); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

把Web Api设为启动项目,打开:http://localhost:5001/swagger/index.html访问Swagger帮助页面:

如果要在应用程序的根目录(http://localhost:<port>/)提供Swagger UI ,请将RoutePrefix属性设置为空字符串:

app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty;
});

顺便我们把launchSettings.json"launchUrl": "weatherforecast",删掉,这个是在浏览器中启动的默认URL。然后我们再次启动,就可以直接看到Swagger的帮助页面了。

添加库IdentityServer4.AccessTokenValidation

Web Api配置Identity Server就需要对token进行验证, 这个库就是对access token进行验证的. 通过NuGet安装:

在Startup的ConfigureServices里面注册配置:

官方文档的配置:

    public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(); services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://localhost:5001"; options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});
}

官方文档的这个配置是不进行验证Api的Scope和其他一些配置的,也就是只要我拿到Access Token就可以访问了。但实际情况应该是我们可能存在多个api项目,有些只能访问api1、有些只能访问api2。

我们的配置,完整的Web Api Startup.cs

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models; namespace IdentityServer4.WebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.Authority = "http://localhost:5000";
options.Audience = "api1";
}); // Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
} // 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.UseAuthentication(); // Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty;
}); app.UseRouting(); //授权
app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

AddAuthentication:将身份验证服务添加到DI并配置Bearer为默认方案。

UseAuthentication 将身份验证中间件添加到管道中,以便对主机的每次调用都将自动执行身份验证。

UseAuthorization 添加了授权中间件,以确保匿名客户端无法访问我们的API端点。

添加[Authorize]属性:

打开WeatherForecastController, 在Controller上面添加这个属性:

然后我们打开:http://localhost:5001/weatherforecast

401意思是未授权

HTTP状态码:https://www.runoob.com/http/http-status-codes.html

所以我们首先需要获取到一个token。那就需要把上一节的Authorization Server也跑起来。解决方案右键,启动项目设置为多个启动项目,AuthServer项目放前面。

然后运行, 使用Postman先获取token:

然后复制一下 access_token的值。新建一个Web Api项目的请求, 把access_token贴到Authorization选择TYPE为Bearer Token的Token里去。

然后,我们就看到请求成功啦~。

验证下范围

还记得我们Web Api的Startup.cs中配置的当前Api为api1,他是和我们AuthServer项目的配置统一的,现在我们改为api2试一下,找一个不存在的,验证下是否还能访问Api接口。

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.Authority = "http://localhost:5000";
options.Audience = "api2";
});

重新运行项目,获取token,访问api

可以看到,token是可以正常获取的,但是我们不能访问api了。

分析一下Token

去https://jwt.io/ 可以分析一下这个token,感兴趣的可以自己了解下,这块资料很多的还是。

End

虽然系列内容基本是参考杨旭老师的,但是真的写起来还是满费力气的,在这里谢谢杨老师,另外B站有杨老师完整版的Identity Server4视频,大家可以去看下哦~

推广下自己的公众号一个逗逼的程序员,主要记录自己工作中解决问题的思路分享及学习过程中的笔记。绝对不会程序员贩卖程序员的焦虑来割韭菜

ASP.NET Core3.1使用Identity Server4建立Authorization Server-2的更多相关文章

  1. ASP.NET Core3.1使用Identity Server4建立Authorization Server

    前言 网上关于Identity Server4的资料有挺多的,之前是一直看杨旭老师的,最近项目中有使用到,在使用.NET Core3.1的时候有一些不同.所以在此记录一下. 预备知识: https:/ ...

  2. 从头编写asp.net core 2.0 web api 基础框架 (5) + 使用Identity Server 4建立Authorization Server (7) 可运行前后台源码

    前台使用angular 5, 后台是asp.net core 2.0 web api + identity server 4. 从头编写asp.net core 2.0 web api 基础框架: 第 ...

  3. 使用Identity Server 4建立Authorization Server (1)

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 本文内容基本完全来自于Identity Server 4官方文档: https://identitys ...

  4. 使用Identity Server 4建立Authorization Server

    使用Identity Server 4建立Authorization Server (6) - js(angular5) 客户端 摘要: 预备知识: http://www.cnblogs.com/cg ...

  5. 三、IDS4建立authorization server

    建立authorization server 一.环境搭建 1.创建项目 2.引用NuGet的identityserver4 3.配置asp.net core 管道 打开Startup.cs, 编辑C ...

  6. 使用Identity Server 4建立Authorization Server (3)

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第二 ...

  7. 使用Identity Server 4建立Authorization Server (5)

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第二 ...

  8. 使用Identity Server 4建立Authorization Server (6) - js(angular5) 客户端

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第二 ...

  9. 使用Identity Server 4建立Authorization Server (2)

    第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第一部分主要是建立了一个简单的Identity Server. 接下来继续: 建立Web Api项目 ...

随机推荐

  1. 使用python解线性矩阵方程(numpy中的matrix类)

    这学期有一门运筹学,讲的两大块儿:线性优化和非线性优化问题.在非线性优化问题这里涉及到拉格朗日乘子法,经常要算一些非常变态的线性方程,于是我就想用python求解线性方程.查阅资料的过程中找到了一个极 ...

  2. Jmeter系列(21)- 详解 HTTP Request

    如果你想从头学习Jmeter,可以看看这个系列的文章哦 https://www.cnblogs.com/poloyy/category/1746599.html HTTP Request 介绍 用来发 ...

  3. ThinkPHP6 上传图片代码demo

    本文展示了ThinkPHP6 上传图片代码demo, 代码亲测可用. HTML部分代码 <tr> <th class="font-size-sm" style=& ...

  4. Java中的final关键字解析

    一.final关键字的基本用法 1.修饰类   当用final修饰一个类时,表明这个类不能被继承.注意: final类中的成员变量可以根据需要设为final, final类中的所有成员方法都会被隐式地 ...

  5. spring boot actuator监控需要注意的点

    1. /metrics接口提供的信息进行简单分类如下表: 分类 前缀 报告内容 垃圾收集器 gc.* 已经发生过的垃圾收集次数,以及垃圾收集所耗费的时间,适用于标记-清理垃圾收集器和并行垃圾收集器(数 ...

  6. vue全家桶(2.3)

    3.4.嵌套路由 实际生活中的应用界面,通常由多层嵌套的组件组合而成.同样地,URL 中各段动态路径也按某种结构对应嵌套的各层组件,例如: 再来看看下面这种更直观的嵌套图: 接下来我们需要实现下面这种 ...

  7. Mariadb之日志相关配置

    前面我们聊到了mariadb的事务,以及事务隔离级别,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/13198186.html:今天我们来聊一聊mariadb的 ...

  8. Python数据分析帮你清晰的了解整理员工们的工作效率和整体满意度

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 项目背景 2018年,被称为互联网的寒冬之年.无论大小公司,纷纷走上了裁员 ...

  9. 二.2vueadmin-template反向代理/路由配置,idc增查删

    一.反向代理: (1)F:\devops\data\web\vueAdmin-template\config\index.js ---让别人也能访问我的vue前端 host: '0.0.0.0', ( ...

  10. python基础知识-1

    1.python是静态的还是动态的?是强类型还弱类型? python是强类型的动态脚本语言: 强类型:不允许不同类型相加 动态:不使用显示类型声明,且确定一个变量的类型是在第一次给它赋值的时候 脚本语 ...