簡體   English   中英

在 asp.net 核心中使用身份時未找到具有授權屬性的操作

[英]Not Found for actions with Authorize attribute while using identity in asp.net core

正如我在標題中提到的,當我將 Identity 添加到我的 ASP.Net Core Web API 項目時,對於在其之上具有 Authorize 屬性的操作,我收到 NotFound 錯誤。
我檢查了這個問題,但我仍然不知道我做錯了什么。

為了簡單起見,我創建了這個控制器:

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
    [Authorize(Roles = "test")]
    public ActionResult<string> Get(string name)
    {
        return Ok($"Hello {name}");
    }
}

這是我在 Startup.cs 中的代碼:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
    {
        options.UseSqlServer(Configuration.GetConnectionString("SqlServer"));
    });
    services.AddControllers();

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        var secretKey = Encoding.UTF8.GetBytes(settings.SecretKey);
        var encriptionKey = Encoding.UTF8.GetBytes(settings.EncriptKey);

        options.TokenValidationParameters = new TokenValidationParameters()
        {
            ClockSkew = TimeSpan.FromMinutes(settings.ClockSkewMinutes),
            IssuerSigningKey = new SymmetricSecurityKey(secretKey),
            TokenDecryptionKey = new SymmetricSecurityKey(encriptionKey),
            // some other options
        };

        options.IncludeErrorDetails = false;
        options.RequireHttpsMetadata = true;
        options.SaveToken = true;
    });

    /* When I remove this code then it works */
    services.AddIdentity<User, Role>(options =>
    {
        // options
    }).AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...

    app.UseRouting();
    app.UseHttpsRedirection();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

更多信息:

  • 當我從操作上方的 Authorize 屬性中刪除Role屬性時,它就會起作用
  • 當我刪除 AddIdentity 時,它可以工作。

這個問題有兩個原因,至少我知道其中的兩個:


未定義DefaultChallengeScheme

使用

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).
         .AddJwtBearer

而不是使用

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; // < this is the key
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer

您必須定義DefaultChallengeScheme屬性,該屬性被IAuthenticationService.ChallengeAsync()用作默認方案

挑戰指定的認證方案。 當未經身份驗證的用戶請求需要身份驗證的端點時,可以發出身份驗證質詢。


添加訂單

(你的錯誤)添加服務的順序很重要。 在這里,您首先添加JWT然后添加Identity ,它會覆蓋您在JWT所做的設置。 您可以在最后添加JWT

-------------------------------------------------- --------------------

並覆蓋您可以使用的操作的默認設置

[Authorize(Roles = "admin", AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

或者

[Authorize(Roles = "admin", AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM