简体   繁体   English

AspNetCore 默认授权用户未通过身份验证

[英]AspNetCore Default Authorization User not authenticated

Using: dotnet-core 3.1使用:dotnet-core 3.1

I have an application where we are trying to add some authentication.我有一个应用程序,我们正在尝试添加一些身份验证。 Authorization seems to be calling all of our appropriate pieces but still throws an authorization error saying the user is not authenticated.授权似乎正在调用我们所有适当的部分,但仍然会引发授权错误,说明用户未通过身份验证。

The user exists in the database and the authentication handler even finishes and does it's thing.用户存在于数据库中,身份验证处理程序甚至完成并完成它的事情。 But for some reason, they are not being authenticated even though the authentication handler seems to be doing it's thing.但是由于某种原因,即使身份验证处理程序似乎正在做这件事,它们也没有得到身份验证。

Startup.cs启动.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测试认证.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: Controller:

public class TestAuthController : Controller
{
  [Authorize]
  public JsonResult Test()
  {
    return new JsonResult(HttpContext.User.Claims.Select(c => c.Type + " - " + c.Value));
  }
}

When I make a call to the endpoint, I get a 401 unauthorized.当我向端点拨打电话时,我收到未经授权的 401。 The log in the server console looks like so:服务器控制台中的日志如下所示:

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

I realized that the issue was that I was not passing the authentication scheme into the ClaimsIdentity.我意识到问题在于我没有将身份验证方案传递给 ClaimsIdentity。

So the ticket instantiation in the authentication handler looks like this:因此身份验证处理程序中的票证实例化如下所示:

var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims, "TestScheme")), "TestScheme");

instead of代替

var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims)), "TestScheme");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用户通过身份验证后,Razor 页面授权未加载页面 - Razor page authorization not loading page when user is authenticated 找不到类型 Microsoft.AspNetCore.Components.Authorization.AuthorizeRouteView 的 Blazor 默认构造函数 - Blazor Default constructor not found for type Microsoft.AspNetCore.Components.Authorization.AuthorizeRouteView Microsoft.AspNetCore.Authorization.DefaultAuthorizationService - 授权失败 - Microsoft.AspNetCore.Authorization.DefaultAuthorizationService - Authorization failed c# - 如何访问“Microsoft.AspNetCore.Authorization”授权用户的详细信息 - c# - how can I access an `Microsoft.AspNetCore.Authorization` authorised user's details 向 AspNetCore Azure 身份验证应用程序添加自定义声明 - Adding Custom Claims to AspNetCore Azure Authenticated Application 没有 AspNetCore 身份的角色和策略授权? - Role and Policy Authorization without AspNetCore Identity? 获取当前用户(aspnetcore 身份) - Getting the current user (aspnetcore identity) 获取Intranet身份验证用户 - Get intranet authenticated user 用户未通过身份验证服务器 4 - User is not authenticated identity server 4 MVC在经过身份验证的页面上显示已验证的用户信息 - MVC Display Authenticated User Information on Authenticated pages
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM