Search code examples
angularauthenticationfrontenduserid

userID is undefined when passing authentication


I can login and i can get token and username, but userID in undefined. i can console log all users data username and token, but userId is undefined. i am using entity framework at the backend and creating user without id, but i even tried with id and it also doesn't work .

what can be the reason ?

login(username: string, password: string): Observable<boolean> {
    return this.http.post<any>(environment.apiUrl + '/token', {username, password})
      .pipe(map(response => {
        const token = response.token;
        const userID = response.userID;
        console.log(userID);
        // login successful if there's a jwt token in the response
        if (token) {
          // store username and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify({userID, username, token}));
          // return true to indicate successful login
          return true;
        } else {
          // return false to indicate failed login
          return false;
        }
      }));
  }

Backend:

User admin = ctx.Users.Add(new User()
            {
                UserId = 1, (try without it and with)
                Username = "admin",
                PasswordHash = passwordHashAdmin,
                PasswordSalt = passwordSaltAdmin,
                IsAdmin = true,

            }).Entity;

Solution

  • Javascript is case sensitive.

    In your C# model you have :

    UserId = 1, (try without it and with)
    

    Which I presume you are using camelCase so will be returned from the API as userId.

    In Javascript you have :

    response.userID;
    

    Notice how the D is capital. Change this to lowercase.

    Also you could have caught this earlier if you just did :

    console.log(response);
    

    To check the entire returned payload.