user_xyz.LOL
user_xyz.LOL

Reputation: 337

angular not reading token from backend server

I am working with angular and I can see the token is being relayed properly from backend server but angular is not able to read with below code

import { IServerAuthResponse } from './auth.service';
import { CCommonUrl } from './../../shared/util/CCommonUrl';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ROLE } from './role.enum';
import { Observable, BehaviorSubject, throwError, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import * as decode from 'jwt-decode';
import { transformError } from 'src/app/shared/common/common';

export interface IAuthStatus {
    isAuthenticated: boolean;
    userId: number;
    userRole: ROLE;
}

export interface IServerAuthResponse {
    accessToken: string;
}

const defaultStatus: IAuthStatus = {
    isAuthenticated: false,
    userId: null,
    userRole: ROLE.NONE
};

@Injectable({
    providedIn: 'root'
})
export class AuthService {

    public authProvider: (
        username: string,
        password: string
    ) => Observable<IServerAuthResponse>;

    authStatus = new BehaviorSubject<IAuthStatus>(defaultStatus);
    constructor(
        private http: HttpClient
    ) {
        this.authProvider = this.mtAuthProvider;
    }

    private mtAuthProvider(
        username: string,
        password: string
    ): Observable<IServerAuthResponse> {


        const authorization: IServerAuthResponse = { accessToken: '' };
        this.http.post<any>(CCommonUrl.LOGIN, {
            username,
            password
        }, { observe: 'response' }).subscribe((res) => {
            authorization.accessToken = res.headers.get('Authorization');
            // Authorization
        });
        return of(authorization);
    }
    public login(username: string, password: string): Observable<IAuthStatus> {
        const loginResponse = this.authProvider(username, password).pipe(
            map(value => {
                console.log('accesstoken==>', value.accessToken);
                return decode(value.accessToken) as IAuthStatus;
            }), catchError(transformError)
        );


        loginResponse.subscribe(
            res => {
                console.log('res', res);
                this.authStatus.next(res);
            }, err => {
                this.logout();
                return throwError(err);
            }
        );
        return loginResponse;
    }

    public logout(): void {
        this.authStatus.next(defaultStatus);
    }
}

When I am checking with postman everything is working fine. Please take a look

I am new to angular and I am posting this code I am using. It is unable to recive token and I am unable to figure out why.

Please look into it and if I need to change something please let me know.

Another thing is that this api is hitting backend server. I verified myself from server logs.

Upvotes: 0

Views: 83

Answers (1)

JB Nizet
JB Nizet

Reputation: 692121

There might be some other issues, but this is definitely incorrect:

    const authorization: IServerAuthResponse = { accessToken: '' };
    this.http.post<any>(CCommonUrl.LOGIN, {
        username,
        password
    }, { observe: 'response' }).subscribe((res) => {
        authorization.accessToken = res.headers.get('Authorization');
        // Authorization
    });
    return of(authorization);

You're returning an observable that immediately emits { accessToken: '' }. And then much later, when the http response finally comes back, you cange the value of the accessToken.

Replace that by

return this.http.post<any>(CCommonUrl.LOGIN, { username, password }, { observe: 'response' })
  .pipe(
    map(res => ({ accessToken: res.headers.get('Authorization' }))
  );

Upvotes: 1

Related Questions