配套源码:https://gitee.com/jardeng/IdentitySolution
接上一篇《ASP.NET Core3.1使用IdentityServer4中间件系列随笔(一):搭建认证服务器》
1、创建API项目并运行。
使用API模板,API模板中自带了一个示例。
创建完成后的项目截图
设置WebApplication1为启动项,运行起来后,默认访问的是:http://localhost:5000/weatherforecast
可以看到这个api返回了一些测试数据
此时API没有受保护,可以任意访问,接下来配置IdentityServer来保护API。
2、首先添加nuget包:Microsoft.AspNetCore.Authentication.JwtBearer。
3、在Startup.cs类ConfigureServices方法中,将身份验证服务添加到DI并配置Bearer为默认方案。
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //将身份验证服务添加到DI并配置Bearer为默认方案。 services.AddAuthentication("Bearer") .AddJwtBearer("Bearer", options => { options.Authority = "http://localhost:5000"; options.RequireHttpsMetadata = false; options.Audience = "api1"; }); }