JWT and Angular 7 returning Token null value in the application

Asked

Viewed 339 times

0

My JWT application has the following code:

my Model of user:

export class User {
    id: number;
    username: string;
    password: string;
    name: string;
    admin: boolean;
    token?: string;
}

The ts of the Login is:

this.authenticationService.login(this.f.username.value, this.f.password.value, this.fingerprint, this.admin)
      .pipe(first())
      .subscribe(
        user => {
          this.router.navigate(['/']);
        },
        error => {
          this.error = error;
          this.loading = false;
        });
  }

My headline is like this:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json;charset=UTF-8',
    'Accept-Language': '1'
  }),
};

The login call is like this:

 login(username: string, password: string, fingerprint: string, admin: boolean) {
    return this.http.post<any>("http://site.com/url/login", { username, password, admin, fingerprint}, httpOptions)
            .pipe(map(user => {
                // login successful if there's a jwt token in the response
              console.log("USER: " + user);

                if (user) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));
                    this.currentUserSubject.next(user);
                }

                return user;
            }));
    }

my contractor is like this:

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        let currentUser = this.authenticationService.currentUserValue;

        if (currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: {
                  'Authorization': `Bearer ${currentUser.token}`,
                  'Accept-Language': '1'
                }
            });
        }

        return next.handle(request);
    }

Accessing the network tab. It does the request and returns 200 normally and the token appears in the header, but when I try to use the map to get the answer, in the application it is returning null. I have tested several methods and continues as null.

I’m making based on the jasonwatmore code of angular jwt 7;

Below is the return 200 and the token

inserir a descrição da imagem aqui

Someone’s been through it?

3 answers

1


From what I understand, your problem is getting access to your JWT token in the answer of your login POST call, right?

In this case, for it to work the way it expects, the implementation would have to be similar to the one I put below.

O ts de login:

this.authenticationService.login(this.f.username.value, this.f.password.value, this.fingerprint, this.admin)
      .subscribe(
        user => {
          this.router.navigate(['/']);
        },
        error => {
          this.error = error;
          this.loading = false;
        });
  }

Header:

   const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json;charset=UTF-8',
        'Accept-Language': '1'
      }),
      observe: 'response'
    };

Login service:

    login(username: string, password: string, fingerprint: string, admin: boolean) {
        return this.http.post<any>("http://site.com/url/login", { username, password, admin, fingerprint}, httpOptions)
                .pipe(map(response => {
                  let user = {token: response.headers.Authorization}
                  // login successful if there's a jwt token in the response
                  console.log("USER: " + user);

                    if (user) {
                        // store user details and jwt token in local storage to keep user logged in between page refreshes
                        localStorage.setItem('currentUser', JSON.stringify(user));
                        this.currentUserSubject.next(user);
                    }

                    return user;
                }));
        }

Interceptor:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        let currentUser = this.authenticationService.currentUserValue;

        if (currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: {
                  'Authorization': `${currentUser.token}`,
                  'Accept-Language': '1'
                }
            });
        }

        return next.handle(request);
    }
  • Opa, like this it returns a [Object Object] in the console, but in this collection it does not pass to the Interceptor it from the error in: this.currentUserSubject.next(user); no service. , the error is: Argument of type '{ token: any; }' is not Assignable to Parameter of type 'User'. Type '{ token: any; }' is Missing the following properties from type 'User': id, username, password, name, admin

  • obs. no note I put: note: 'Answer' as 'body', only answer if it gave an error

  • I managed to print the token with your help, but doing so: . pipe(map((Answer: Httpresponse<any>) => { console.log("USER: " + Answer.headers.get('Authorization')); Now I need to fix this part of this.currentUserSubject.next(user)

  • Just modify the User model to accept a token property, and pass the other required properties to it in the login service creation. Qto on note: 'Replay' as 'body', should work as well.

  • Oops! Vlw bro!! It worked here, saved me!

0

I think you do not need to pass a new header at the time of the POST, because you are already setting in the Third Party, I think it may be being replaced and running out of Token. Try to do the post by just passing the URL and BODY.

  • The backend is sending the token directly in the header, in body it has nothing at all.. Even without sending httpOptions it returns null

-1

The login function is returning an HTTP request, how is the implementation of this Observable Subscription? To access the response header, you would need to add the 'note: "Response"' property to the httpOptions object. Thus, your user would have all the information from the POST response. It would be interesting to post more code details and, if possible, contract details of this HTTP call, allowing a better understanding of your problem.

  • Hello, I’m making the call based on https://jasonwatmore.com/post/2018/10/29/angular-7-user-registration-registration-login-example-tutorial but with the fake backend it works, but when I point to api, it returns 200 ok, but I can’t get this get.

  • I updated the question in more detail.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.