簡體   English   中英

成功登錄Angular后重定向

[英]Redirect after successful login Angular

我有 Spring Boot 應用程序作為 API,其中我使用 oauth2 進行身份驗證。(不記名令牌......)。 在我的角度應用程序中,我有一個身份驗證攔截器:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (localStorage.getItem('currentUser') != null) {
  req = req.clone({
    headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('currentUser'))
  });
} else if (localStorage.getItem('currentUser') == null) {
  this.router.navigateByUrl('/login');
  return next.handle(req.clone());
}
return next.handle(req).pipe(
  // we can check the status of the exception. And depending on the status,
  // we can decide what we should do.
  catchError((error: HttpErrorResponse) => {
    return throwError(error.error);
  }),
  // We could check the type of object/error to show
  // in our case to send error from backend to front
  tap((succ) => {
    },
    (err) => {
      if (err.status === 500) {
        return next.handle(req.clone());
      }
    }),
);
}

一個身份守衛:

canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
const url: string = state.url;
return this.checkLogin(url);

}

canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
 return this.canActivate(route, state);
}

checkLogin(url: string) {

if (this.authService.isLoggedIn()) {
  return true;
}
this.authService.redirectUrl = url;
this.router.navigate(['/login'], {queryParams: { returnUrl: url }} );
return false;
}

最后是我的登錄 ts 文件中的登錄功能:

onSubmit() {
localStorage.clear();
this.authService.login(this.loginForm.value.username, this.loginForm.value.password)
  .subscribe((dataReceived: any) => {
      console.log("test login"+dataReceived)
      localStorage.setItem('currentUser', dataReceived.access_token);
      localStorage.setItem('expiredIn', dataReceived.expires_in);
      localStorage.setItem('refreshToken', dataReceived.refresh_token);
      const expireDate = new Date(new Date().getTime() + (1000 * dataReceived.expires_in));
      localStorage.setItem('dateExpiration', expireDate.toString());
      this.router.navigate(['/']);
    },
    (err: HttpErrorResponse) => {
      if (err) {
        this.error = 'login.login_msg';
      }
    });

}

成功登錄后,我不會被重定向到主頁 url。(我確信憑據和登錄成功,因為當我從 url 欄中刪除 '/login' 時,我被重定向到主頁)。

這是我的身份驗證服務 ts 代碼:

  public storedToken: string;
/**
 * constructor
 * @param HttpClient httpClient
 */
constructor(private httpClient: HttpClient) {

  // set token if saved in local storage
  this.storedToken = localStorage.getItem('currentUser');
}
redirectUrl: string;
/**
 * login
 * @param username the username
 * @param password the password
 */
login(username: string, password: string) {

  const data = '?grant_type=password&username=' + username + '&password=' + password;
  let reqHeader = new HttpHeaders();
  reqHeader = reqHeader.append('Content-Type', 'application/json')
    .append('Authorization', 'Basic ' + btoa(environment.authentificationUserName + ':' + environment.authentificationPassword));
  return this.httpClient.post(PfeUrlConstants.AUTHENTICATION_URL_API + data, {}, {headers: reqHeader})
    .pipe(
      catchError((error: HttpErrorResponse) => {
        return throwError(error.error);
      }),
    );
}

/**
 * get curentUser
 */
curentUser() {
  return this.httpClient.get<User>(PfeUrlConstants.USER_INFOS);
}

isLoggedIn() {
  if (this.storedToken) {
    return true;
  }
  return false;
}

getAuthorizationToken() {
  const currentUser = JSON.parse(this.storedToken);
  return currentUser.token;
}

/**
 * Logout
 */
logout() {
  return this.httpClient.post(PfeUrlConstants.LOGOUT_URL_API,{});
}

/**
 * The client authentication method
 */
clientAuthentication() {
  const data = 'grant_type=client_credentials';
  const url = PfeUrlConstants.AUTHENTICATION_URL_API + data;
  let reqHeader = new HttpHeaders();
  reqHeader = reqHeader.append('Authorization', 'Basic '
    + btoa(environment.authentificationUserName + ':' + environment.authentificationPassword));
  return this.httpClient.post(url, {}, {headers: reqHeader});
}

在 AuthService 的 isLoggedIn() 中,只需使用此更改更新 If 條件。

localStorage.getItem('currentUser')

更新后您的方法將如下所示

isLoggedIn() {
  if (localStorage.getItem('currentUser')) {
    return true;
  }
  return false;
}

我相信當您在組件中使用 AuthService 時,您創建的變量會盡快初始化,所以最初它是未定義的,這就是為什么條件總是返回 false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM