配套源码:https://gitee.com/jardeng/IdentitySolution

 

接上一篇《ASP.NET Core3.1使用IdentityServer4中间件系列随笔(一):搭建认证服务器

 

1、创建API项目并运行。

ASP.NET Core3.1使用IdentityServer4中间件系列随笔(二):创建API项目,配置IdentityServer保护API资源

使用API模板,API模板中自带了一个示例。

ASP.NET Core3.1使用IdentityServer4中间件系列随笔(二):创建API项目,配置IdentityServer保护API资源

创建完成后的项目截图

ASP.NET Core3.1使用IdentityServer4中间件系列随笔(二):创建API项目,配置IdentityServer保护API资源

 

 设置WebApplication1为启动项,运行起来后,默认访问的是:http://localhost:5000/weatherforecast

可以看到这个api返回了一些测试数据

 ASP.NET Core3.1使用IdentityServer4中间件系列随笔(二):创建API项目,配置IdentityServer保护API资源

此时API没有受保护,可以任意访问,接下来配置IdentityServer来保护API。

2、首先添加nuget包:Microsoft.AspNetCore.Authentication.JwtBearer

ASP.NET Core3.1使用IdentityServer4中间件系列随笔(二):创建API项目,配置IdentityServer保护API资源

 3、在Startup.cs类ConfigureServices方法中,将身份验证服务添加到DI并配置Bearer为默认方案。

ASP.NET Core3.1使用IdentityServer4中间件系列随笔(二):创建API项目,配置IdentityServer保护API资源

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";
        });
}
View Code

相关文章: