.Net Core + Angular 2/4身份验证错误

时间:2017-07-09 15:06:43

标签: .net angular authentication core

我使用this website为Angular 2/4使用.net核心api身份验证。

注册有效,但我在身份验证(登录)时出现了令牌错误。服务器给我这个错误:HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request.

这是我的代码:

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

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

谢谢!

1 个答案:

答案 0 :(得分:1)

我找到并解决了错误。

我在项目中实现了Application Insights(.net core web api)。我已经再次要求Angular 2项目提出上述请求了。然后我去了portal.azure.com并在Application Insights的选项卡中打开。我选择了失败的请求以查看更详细的信息。 Anther the Exception标题说:

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文件中。所以我只需要提供更长的密钥。

现在它没有问题!

相关问题