正如我在標題中提到的,當我將 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();
});
}
更多資訊:
- 當我
Role從操作上方的 Authorize 屬性中洗掉該屬性時,它就會起作用 - 當我洗掉 AddIdentity 時,它可以作業。
uj5u.com熱心網友回復:
這個問題有兩個原因,至少我知道其中的兩個:
沒有定義 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)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354930.html
