【问题标题】:.NET Core + Angular 2/4 Authentication Error.NET Core + Angular 2/4 身份验证错误
【发布时间】:2017-12-13 08:23:07
【问题描述】:

我正在使用 this website 为 Angular 2/4 使用 .NET Core API 身份验证。

注册有效,但在身份验证(登录)时令牌出现错误。服务器给了我这个错误:

HTTP500: SERVER ERROR - 服务器遇到了阻止它完成请求的意外情况。

这是我的代码:

[AllowAnonymous]
[HttpPost]
public IActionResult Authenticate([FromBody]ApplicationUserDto applicationUserDto)
{
    var appUser = _appUserService.Authenticate(applicationUserDto.Username, applicationUserDto.Password);
        
    if (appUser == null)
        return Unauthorized();
        

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

    var token = tokenHandler.CreateToken(tokenDescriptor); //Here returns the Error
    var tokenString = tokenHandler.WriteToken(token);

    // return basic user info (without password) and token to store client side
    return Ok(new
    {
        Id = appUser.Id,
        Username = appUser.Username,
        FirstName = appUser.FirstName,
        LastName = appUser.LastName,
        Token = tokenString
    });
    }

我不知道是什么问题。我使用该网站仔细编写了代码(不是复制粘贴)。有什么问题?

【问题讨论】:

    标签: angular authentication .net-core


    【解决方案1】:

    我发现并解决了错误。

    我已经在项目中实现了 Application Insights (.NET Core Web API)。我已经从 Angular 2 项目再次请求了上述请求。然后我去了 portal.azure.com 并在一个选项卡中打开了 Application Insights。我选择了失败的请求以查看更多详细信息。花药异常标题说:

    System.ArgumentOutOfRangeException at MyProject.Controllers.ApplicationUsersController.Authenticate.

    然后我点击它以获取更多详细信息,然后我发现了问题:

    IDX10603: The algorithm: 'http://www.w3.org/2001/04/xmldsig-more#hmac-sha256' requires the SecurityKey.KeySize to be greater than '128' bits. KeySize reported: '64'. Parameter name: key.KeySize

    密钥保存在 appsettings.json 文件中。所以我只需要提供更长的密钥。

    现在可以正常使用了!

    【讨论】:

      猜你喜欢
      • 2017-06-26
      • 2018-11-24
      • 2020-04-06
      • 1970-01-01
      • 2019-03-14
      • 2017-07-27
      • 2020-09-05
      • 2020-10-08
      • 1970-01-01
      相关资源
      最近更新 更多