Mike Ross
Mike Ross

Reputation: 2972

Ionic Angular Auth Interceptor not working

I have following auth service file

export class AuthService {

    url = environment.url;
    user = null;
    authenticationState = new BehaviorSubject(false);

    constructor(private http: HttpClient, private helper: JwtHelperService, private storage: Storage,
                private plt: Platform, private alertController: AlertController) {
        this.plt.ready().then(() => {
            this.checkToken();
        });
    }

    getToken() {
        return this.storage.get(TOKEN_KEY).then(token => {
           return token;
        });
    }

    checkToken() {
        this.storage.get(TOKEN_KEY).then(token => {
            if (token) {
                let decoded = this.helper.decodeToken(token);
                let isExpired = this.helper.isTokenExpired(token);
                if (!isExpired) {
                    this.user = decoded;
                    this.authenticationState.next(true);
                } else {
                    this.storage.remove(TOKEN_KEY);
                }
            }
        });
    }

    register(credentials) {
        return this.http.post(`${this.url}/auth/register`, credentials).pipe(
            catchError(e => {
                this.showAlert(e.error.msg);
                throw new Error(e);
            })
        );
    }

    login(credentials) {
        return this.http.post(`${this.url}/auth/login`, credentials)
            .pipe(
                tap(res => {
                    this.storage.set(TOKEN_KEY, res['token']);
                    this.user = this.helper.decodeToken(res['token']);
                    this.authenticationState.next(true);
                }),
                catchError(e => {
                    this.showAlert(e.error.msg);
                    throw new Error(e);
                })
            );
    }

    logout() {
        this.storage.remove(TOKEN_KEY).then(() => {
            this.authenticationState.next(false);
        });
    }
}

I am trying to insert access_token with http request using following interceptor


export class AuthInterceptor implements HttpInterceptor {
    constructor(private authService: AuthService) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler) {

        this.authService.getToken().then((accessToken) => {

            req = req.clone({
                setHeaders: {
                    "Content-Type": "application/json",
                    Authorization: "Bearer " + accessToken
                }
            });
        });


        return next.handle(req);
    }
}

But it's not working properly and after login, it logs user out and redirect to login page.

What is my mistake with interceptor?

Thank you

Upvotes: 0

Views: 485

Answers (1)

Andrei
Andrei

Reputation: 12206

in your code return line is evaluated before the callback that updates the request object. to fix that, return should be part of async chain. Fix example:


export class AuthInterceptor implements HttpInterceptor {
    constructor(private authService: AuthService) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler) {

        return from(this.authService.getToken().then((accessToken) => {

            return req.clone({
                setHeaders: {
                    "Content-Type": "application/json",
                    Authorization: "Bearer " + accessToken
                }
            });
        })).pipe(switchMap(newReq => next.handle(newReq)));

    }
}

Upvotes: 1

Related Questions