【问题标题】:Asp.Net Core Identity with AuthorizeAttribute not working for Roles具有 AuthorizeAttribute 的 Asp.Net 核心身份不适用于角色
【发布时间】:2017-07-12 13:36:51
【问题描述】:

因此,我目前在 .Net 核心应用程序中实现了 IdentityServer 4,使用 JWT 不记名令牌进行身份验证。

问题似乎出在使用 [Authorize(Roles = "Admin")] 时,我从日志中得到以下信息:[Information] AuthenticationScheme: "Bearer" was forbidden.

当我只有 [Authorize] 属性时,它可以正常工作。

代码如下:

services.AddDbContext<OmbiContext>(options =>
    options.UseSqlite("Data Source=Ombi.db"));

services.AddIdentity<OmbiUser, IdentityRole>()
    .AddEntityFrameworkStores<OmbiContext>()
    .AddDefaultTokenProviders();

services.AddIdentityServer()
    .AddTemporarySigningCredential()
    .AddInMemoryPersistedGrants()
    .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
    .AddInMemoryApiResources(IdentityConfig.GetApiResources())
    .AddInMemoryClients(IdentityConfig.GetClients())
    .AddAspNetIdentity<OmbiUser>();

services.Configure<IdentityOptions>(options =>
{
    options.Password.RequireDigit = false;
    options.Password.RequiredLength = 1;
    options.Password.RequireLowercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireUppercase = false;
});

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IMemoryCache cache)
{
    app.UseIdentity();
    app.UseIdentityServer();
    app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
    {
        Authority = options.Value.WebsiteUrl,
        ApiName = "api",
        ApiSecret = "secret",

        EnableCaching = true,
        CacheDuration = TimeSpan.FromMinutes(10), // that's the default
        RequireHttpsMetadata = options.Value.UseHttps, // FOR DEV set to false
        AutomaticAuthenticate = true,
        AutomaticChallenge = true    
    });
// etc...
}

创建用户和角色的代码:

 var result = await UserManager.CreateAsync(userToCreate, user.Password);
 if (result.Succeeded)
 {
     if (!(await RoleManager.RoleExistsAsync("Admin")))
     {
         var r = await RoleManager.CreateAsync(new IdentityRole("Admin"));
     }
     var re = await UserManager.AddToRoleAsync(userToCreate, "Admin");
 }

查看数据库中的所有内容都已正确链接,我可以看到,该用户具有正确的角色,但 Authorize 属性仍然不起作用。

编辑

经过一番调查,当我们拥有[Authorize] 属性时,查看控制器上的User 属性,结果如下:

所以看起来我们甚至没有得到用户名或任何关于用户的信息。

【问题讨论】:

    标签: c# asp.net asp.net-core asp.net-identity identityserver4


    【解决方案1】:

    查看您提供的图片,您的声明列表中似乎有 20 个声明。尝试查看您在该列表中看到的角色/声明!

    您可以通过

    获取列表
    var claims = HttpContext.User.Claims.ToList();
    
    foreach (var c in claims)
    {
         Console.WriteLine(c.Type + c.Value);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-23
      • 2020-08-02
      • 2018-08-31
      • 2019-03-02
      • 2019-03-26
      • 2018-02-20
      • 1970-01-01
      • 2021-12-11
      相关资源
      最近更新 更多