使用: dotnet-core 3.1
我有一个应用程序,我们试图在其中添加一些身份验证。授权似乎在调用我们所有适当的部分,但仍然抛出授权错误,表明用户未通过身份验证。
用户存在于数据库中,并且身份验证处理程序甚至完成工作。但是由于某些原因,即使身份验证处理程序似乎正在执行此操作,也未对它们进行身份验证。
Startup.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();
}
TestAuthentication.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));
}
控制器:
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
答案 0 :(得分:1)
我意识到问题是我没有将身份验证方案传递给ClaimsIdentity。
因此,身份验证处理程序中的票证实例化如下:
var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims, "TestScheme")), "TestScheme");
代替
var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims)), "TestScheme");