identityserver4 V4 新版本踩坑

点点圈 提交于 2020-07-29 10:52:03

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  是从 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";
// });





 

 

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

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!