ASP.NET Core身份验证失败

Rog*_*son 2 asp.net authentication

我正在尝试向我的应用程序前端VueJS后端Asp.NET core 2.1添加身份验证,但最终却无法使它真正进行身份验证。

在Asp.NET中设置身份验证:

        var key = Encoding.ASCII.GetBytes("mysecret");
        services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
                        var userId = int.Parse(context.Principal.Identity.Name);
                        var user = userService.GetById(userId);
                        if (user == null)
                        {
                            // return unauthorized if user no longer exists
                            context.Fail("Unauthorized");
                        }
                        return Task.CompletedTask;
                    }
                };
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

        // configure DI for application services
        services.AddScoped<IUserService, UserService>();
Run Code Online (Sandbox Code Playgroud)

我的UserService被模拟为始终返回相同的硬编码用户。

登录时,前端似乎正在发送从后端获取的正确令牌:

在此处输入图片说明

但是,在调用授权端点时,我仍然被拒绝:

在此处输入图片说明

服务器报告以下日志:

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2] Authorization failed. info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3] Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'. info: Microsoft.AspNetCore.Mvc.ChallengeResult[1] Executing ChallengeResult with authentication schemes (). info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[2] Successfully validated the token. info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[12] AuthenticationScheme: Bearer was challenged. info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2] Executed action DnaBackend.Controllers.DnaController.UploadFile (DnaBackend) in 32.891ms info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2] Request finished in 41.847ms 401 info: Microsoft.AspNetCore.Server.Kestrel[32] Connection id "0HLIDVBUA1Q5P", Request id "0HLIDVBUA1Q5P:00000003": the application completed without reading the entire request body.

有什么想法为什么会失败吗?我也正在使用CORS,如果有什么区别(?)。

登录端点如下所示:

    [HttpPost("login")]
    public IActionResult Login([FromForm]LoginRequest loginRequest)
    {

        var user = _userService.Authenticate(loginRequest.Username, loginRequest.Password);

        if (user == null)
            return BadRequest(new { message = "Username or password is incorrect" });

        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new[] 
            {
                new Claim(ClaimTypes.Name, user.Id.ToString())
            }),
            Expires = DateTime.UtcNow.AddDays(7),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        var tokenString = tokenHandler.WriteToken(token);

        // return basic user info (without password) and token to store client side
        return Ok(new LoginResponse(user.Id, user.Username, user.FirstName, user.LastName, tokenString));
    }
Run Code Online (Sandbox Code Playgroud)

Bra*_*ley 7

在我的情况是,我已经把UseAuthorization之前UseAuthentication。

请确保这些方法按以下顺序排列:

app.UseAuthentication();

app.UseAuthorization();
Run Code Online (Sandbox Code Playgroud)


Rog*_*son 5

原来是app.UseAuthentication()在startup.cs中缺少一个的情况

当您还使用来配置服务时,ASP.NET并不完全要求这样做AddAuthentication。

因此,如果其他人遇到相同的问题,您现在知道为什么:-)