[英]AspNetCore Default Authorization User not authenticated
使用:dotnet-core 3.1
我有一個應用程序,我們正在嘗試添加一些身份驗證。 授權似乎正在調用我們所有適當的部分,但仍然會引發授權錯誤,說明用戶未通過身份驗證。
用戶存在於數據庫中,身份驗證處理程序甚至完成並完成它的事情。 但是由於某種原因,即使身份驗證處理程序似乎正在做這件事,它們也沒有得到身份驗證。
啟動.cs
ConfigureServices(...) {
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = "TestScheme";
sharedOptions.DefaultAuthenticateScheme = "TestScheme";
sharedOptions.DefaultChallengeScheme = "TestScheme";
}).AddScheme<TestAuthenticationOptions, TestAuthentication>("TestScheme", options => { });
services.AddAuthorization();
}
Configure() {
app.UseMvc();
app.UseAuthentication();
app.UseAuthorization();
}
測試認證.cs
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
// Get Authorization header value
if (!this.Request.Headers.TryGetValue(HeaderNames.Authorization, out StringValues authorization))
{
return Task.FromResult(AuthenticateResult.Fail("Cannot read authorization header."));
}
List<Claim> claims = new List<Claim> {
new Claim(ClaimTypes.NameIdentifier, authorization.ToString()),
new Claim(ClaimTypes.Name, authorization.ToString()),
new Claim(ClaimTypes.Email, authorization.ToString())
};
// Create authenticated user
var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims)), "TestScheme");
return Task.FromResult(AuthenticateResult.Success(ticket));
}
Controller:
public class TestAuthController : Controller
{
[Authorize]
public JsonResult Test()
{
return new JsonResult(HttpContext.User.Claims.Select(c => c.Type + " - " + c.Value));
}
}
當我向端點撥打電話時,我收到未經授權的 401。 服務器控制台中的日志如下所示:
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:5005/testauth/test
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 3.1.0 initialized 'MyAppContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
dbug: MyApp.API.TestAuthentication[8]
AuthenticationScheme: TestScheme was successfully authenticated.
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed.
info: MyApp.API.TestAuthentication[12]
AuthenticationScheme: TestScheme was challenged.
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 2.5679ms 401
我意識到問題在於我沒有將身份驗證方案傳遞給 ClaimsIdentity。
因此身份驗證處理程序中的票證實例化如下所示:
var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims, "TestScheme")), "TestScheme");
代替
var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims)), "TestScheme");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.