identityserver4 V4 新版本踩坑

identityserver4 的版本前段时间更新到V4,和之前的版本,还是有一些使用的差异;

1. API资源声明,之前版本用的是ApiResource,新版本用的是ApiScope,从名字就可以看出区别,新版是用 Scope 区分的;

        /// <summary>
        /// 新版本
        /// </summary>
        public static IEnumerable<ApiScope> Apis =>
            new List<ApiScope>
            {
                new ApiScope("api1", "my api1"),
            };

        /// <summary>
        /// 旧版本
        /// </summary>
        public static IEnumerable<ApiResource> ApiScopes =>
            new List<ApiResource>
            {
                new ApiResource("api1", "my api1"),
            };

2. 如果使用了IdentityServer4 的快速入门的登录等界面代码,这里也有好些要改的,我是测试项目直接复制的新版的快速入门代码

3.因为API声明的地方做了修改,相应的在API的认证授权上也不一样

新版认证的时候不需要设置Audience(Audience在之前版本是指identityserver服务端的ApiResource)

新版本 的Audience  是从 Claim 中获取的,需要添加对应的授权

// 新版API认证

services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
  options.Authority = "http://localhost:5000";
  options.RequireHttpsMetadata = false;

  options.TokenValidationParameters = new TokenValidationParameters
  {
    ValidateAudience = false
  };
});

// API授权
services.AddAuthorization(options =>
{
  options.AddPolicy("ApiScope", policy =>
  {
    policy.RequireAuthenticatedUser();
    policy.RequireClaim("scope", "api1");
  });
});

// 旧版 

services.AddAuthentication(options =>
{
  options.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
  options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
  options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
  options.DefaultSignInScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
  options.DefaultForbidScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
})
.AddIdentityServerAuthentication(options =>
{
  options.Authority = IdentityUrl;
  options.ApiName = "orderapi";
  options.RequireHttpsMetadata = false;
});

// 旧版也有这个写法

//services.AddAuthentication("Bearer")
// .AddJwtBearer("Bearer", options =>
// {
// options.Authority = IdentityUrl;
// options.RequireHttpsMetadata = false;
// options.Audience = "orderapi";
// });

 

从我目前的使用上来说大体上就这里需要注意

原文地址:https://www.cnblogs.com/zhanghm1/p/13366458.html