[英]Asp.net core 5, using Identity, how do I change the default redirect of the [Authorize] Attribute?
[英]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();
});
}
更多信息:
Role
屬性時,它就會起作用這個問題有兩個原因,至少我知道其中的兩個:
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.