首页 > 解决方案 > 成功登录后角度无法重定向用户

问题描述

我正在使用 anuglar 进行基本操作auth,并且我从后端获取令牌,存储在本地缓存中但无法将用户重定向到其他页面,因为我有以下代码interceptor

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {

    constructor(private authService: AuthService, private router: Router) {

    }

    intercept(req: HttpRequest<any>, next: HttpHandler):
        Observable<HttpEvent<any>> {
        const jwt = this.authService.getToken();
        console.log(jwt);
        const authRequest = req.clone({
            setHeaders: {
                Authorization:
                    `${jwt}`
            }
        });

        console.log('token request: ', authRequest.headers.get('Authorization'))
        return next.handle(authRequest).pipe(
            catchError((err, caught) => {
                if (err.status === 401) {
                    this.router.navigate(['/login'], {
                        queryParams: {
                            redirectUrl:
                                this.router.routerState.snapshot.url
                        },
                    });
                }
                return observableThrowError(err);
            })
        );
    }
}

这是我的身份验证服务:

export class AuthService extends CacheService {

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

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

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


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

    private decodedToken(jwt: string): IAuthStatus {

        let decoded = decode(jwt) as IAuthStatus;
        console.log(decoded);
        return decoded;
    }


    public login(username: string, password: string): Observable<IAuthStatus> {
        let decodedToken = null;
        const loginResponse = this.authProvider(username, password).pipe(
            map(value => {
                this.setToken(value.accessToken);
                decodedToken = decode(value.accessToken);
                // return decode(value.accessToken) as IAuthStatus;
                return this.decodedToken(value.accessToken);
            }), catchError(transformError)
        );


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

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

    private setToken(jwt: string) {
        this.setItem('jwt', jwt);
    }
    private getDecodedToken(): IAuthStatus {
        return decode(this.getItem('jwt'));
    }
    getToken(): string {
        return this.getItem('jwt') || '';
    }

    private clearToken() {
        this.removeItem('jwt');
    }


}

我下面是我的其他接口+常量

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

export interface IServerAuthResponse {
    accessToken: string;
}

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

以下是我从有效载荷中得到的信息:

{ exp:1566392597 sub:“用户”}

用令牌作为

承载 eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJBbWFuSFIiLCJleHAiOjE1NjYzOTI0ODl9.hocUR6JZxyyoVZlax_wW-C28eRNW5DyiJDIZuXwLwvGDNGzyr1FmdrS_inGd-VIVxyIf6cWpwhydkO1EDh_ruQ

现在的问题是,用户应该导航到/url,因为它已经过身份验证但不是。

你能指导我如何解决这个问题。

我是角度新手,后端在Spring boot

编辑:如果需要更多信息,请告诉我。

标签: typescriptangular8

解决方案


您必须在 AuthService 中注入路由器并在成功登录响应时调用导航

import { Router } from '@angular/router';
 constructor(
    private router: Router,
   )

成功响应 => 保存令牌并导航到主页 URL:

this.router.navigate(['/']);

推荐阅读