GSeriousB
GSeriousB

Reputation: 251

.NET Core + Angular 2/4 Authentication Error

I'm using this website to use .NET Core API authentication for Angular 2/4.

The registration works, but I have an error with the token at the authentication (login). The server gives me this error:

HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request.

Here is my code:

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

I don't know what is the problem. I carefully wrote the code (not copy paste) using the website. What is the problem?

Upvotes: 1

Views: 233

Answers (1)

GSeriousB
GSeriousB

Reputation: 251

I've found and resolved the error.

I've implemented Application Insights in the project (.NET Core Web API). I've requested one more time the request above from the Angular 2 project. Then I went portal.azure.com and opened in a tab the Application Insights. I selected the failed request to see more detailed. Anther the Exception title said:

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

Then I clicked on it for more details and there I found the problem:

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

The Key is saved in the appsettings.json file. So I only had to give a longer Secret Key.

Now it's working with no problem!

Upvotes: 1

Related Questions