Asp.NET Core身份验证失败

时间:2018-11-19 09:07:54

标签: 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>();

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

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

enter image description here

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

enter image description here

服务器报告以下日志:

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));
    }

2 个答案:

答案 0 :(得分:5)

就我而言,是我将UseAuthorization放在UseAuthentication之前。

请确保这些方法的顺序如下:

app.UseAuthentication();

app.UseAuthorization();

答案 1 :(得分:1)

事实证明,这只是在startup.cs中缺少app.UseAuthentication()的情况

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

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