0

I have been struggling with this issue for the past 2 days and I would like your opinions on it.

Method invoking authentication and throwing error:


    this.authService.loginUser('api/accounts/login', userForAuth)
      .subscribe({
        next: (res: AuthResponseDto) => {
          if (res.is2StepVerificationRequired) {
            this.router.navigate(['/authentication/twostepverification'],
              { queryParams: { returnUrl: this.returnUrl, provider: res.provider, email: userForAuth.email } })
          }
          else {
            localStorage.setItem("token", res.token);
            this.authService.sendAuthStateChangeNotification(res.isAuthSuccessful);
            this.router.navigate([this.returnUrl]);
          }
        },
        error: (err: HttpErrorResponse) => {
          console.log(err);
          this.errorMessage = err.error.errorMessage;
         
          this.showError = true;
        }
      })

service

  loginUser(route: string, body: UserForAuthenticationDto) {
    const headers = new HttpHeaders({ 'Content-Type': 'application/json; charset=utf-8' });
    return this.http.post(this.createCompleteRoute(route, environment.backEndURL), body, { headers: headers })
  }

Backend code

[HttpPost("Login")]
        public async Task<IActionResult> Login([FromBody] UserForAuthenticationDto userForAuthentication)
        {
            try
            {


                var user = await _userManager.FindByNameAsync(userForAuthentication.Email);
                if (user == null)
                {
                    Log.Error("Auth API - Login: user null");
                    return BadRequest("Invalid Request");

                }

                if (!await _userManager.IsEmailConfirmedAsync(user))
                {
                    Log.Information("Auth API: - Login - Email not confirmed");
                    return Unauthorized(new AuthResponseDto { ErrorMessage = "Email is not confirmed" });


                }
                if (!await _userManager.CheckPasswordAsync(user, userForAuthentication.Password))
                {
                    await _userManager.AccessFailedAsync(user);

                    if (await _userManager.IsLockedOutAsync(user))
                    {
                        var content = $@"Your account is locked out. To reset the password click this link: {userForAuthentication.ClientURI}";
                        var message = new Message(new string[] { userForAuthentication.Email },
                            "Locked out account information", content, null);

                        await _emailSender.SendEmailAsync(message);
                        Log.Information("Auth API: - Login - Unauthorized locked out");
                        return Unauthorized(new AuthResponseDto { ErrorMessage = "The account is locked out" });
                    }
                    Log.Information("Auth API: - Login - Unauthorized wrong username or password");
                    return Unauthorized(new AuthResponseDto { ErrorMessage = "Incorrect username or password" });
                }

                if (await _userManager.GetTwoFactorEnabledAsync(user))
                {
                    Log.Information("Auth API: - Login - Generating 2 factor authentication");
                    return await GenerateOTPFor2StepVerification(user);
                }

                var token = await _jwtHandler.GenerateToken(user);

                await _userManager.ResetAccessFailedCountAsync(user);

                return Ok(new AuthResponseDto { IsAuthSuccessful = true, Token = token });
            }
            catch (Exception err)
            {
                Log.Error("RegistrLogination API " + err.Message + "OBJ: " + userForAuthentication.ToString());
                return BadRequest(err.Message);
            }
        }

Postman response

{
    "isAuthSuccessful": false,
    "errorMessage": "Incorrect username or password",
    "token": null,
    "refreshToken": null,
    "is2StepVerificationRequired": false,
    "provider": null
}
export interface AuthResponseDto {
    isAuthSuccessful: boolean;
    errorMessage: string;
    token: string;
    is2StepVerificationRequired: boolean;
    provider: string;
}

I get the 401 unauthorized when entering the wrong password but the browser also throws

You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. and err.error is not defined.

i tried using the any type in the observable

I need the errors to display correctly and better understand why this error is occurring to mitigate it in the future

toni
  • 11
  • 2
  • @shrys Actually, i disabled my auth interceptor before posting this because i have that question open in another tab. after you pointing this out again, i realized that i had a loading interceptor which was causing me the issues. i give you credit for this. thanks. its been a long week.... – toni Jan 24 '23 at 08:26

0 Answers0