简体   繁体   English

离子 Angular 身份验证拦截器不起作用

[英]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我正在尝试使用以下拦截器在 http 请求中插入access_token


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谢谢

in your code return line is evaluated before the callback that updates the request object.在更新请求 object 的回调之前评估您的代码return行。 to fix that, return should be part of async chain.为了解决这个问题,return 应该是异步链的一部分。 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)));

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM