Asp.Net Core IdentityServer4 API访问

IdentityServer4 是一个中间件 ,它能够将符合规范的 OpenID Connect 和 OAuth2.0 端点添加到任意一个 ASP.NET Core 应用程序中。详细理论看官网文档

安装IdentityServer4的模板
dotnet new -i IdentityServer4.Templates
使用空模板创建IdentityServer4的服务
dotnet new is4empty -n IdentityServer
打开项目编辑Config

配置里添加一个客户端和保护的api资源

 public static class Config
 {
     public static IEnumerable<IdentityResource> Ids =>
         new IdentityResource[]
         {
             new IdentityResources.OpenId()
         };

     public static IEnumerable<ApiResource> Apis =>
         new ApiResource[]
         {
              new ApiResource("api1", "My API")
         };

     public static IEnumerable<Client> Clients =>
         new Client[]
         {
              new Client
             {
                 ClientId = "client",

                 // 没有交互式用户,请使用clientid / secret进行身份验证
                 AllowedGrantTypes = GrantTypes.ClientCredentials,

                 // 认证加密
                 ClientSecrets =
                 {
                     new Secret("secret".Sha256())
                 },

                 // 客户有权访问的范围
                 AllowedScopes = { "api1" }
             }
         };
 }

创建一个api资源

添加引用
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 3.1.3
加入IdentityServer服务

     services.AddAuthentication("Bearer")
                  .AddJwtBearer("Bearer", options =>
                  {
                      options.Authority = "http://localhost:5000";//IdentityServer的地址
                      options.RequireHttpsMetadata = false;
                      options.Audience = "api1";//对应IdentityServer里的api资源
                  });
    app.UseAuthentication();
    app.UseAuthorization();   


控制器添加验证

添加一个控制台客户端,然后客户端请求IdentityServer 服务获取token,携带token请求相对应的Api资源
添加引用
Install-Package IdentityModel -Version 5.0.0-preview.0

原文地址:https://www.cnblogs.com/SuperDust/p/12757522.html