在 SpringBoot使用JWT集成Ng-Alain中,我們簡單介紹了SpringBoot與Ng-Alain的集成,在這種前後端分離框架實踐中,我們使用了JWT來作爲交互的安全標識,考慮一個問題,從整個系統的業務實際來看,當Token過期失效之後,我們需要用戶重新登錄以獲取新的Token。在我們的代碼實現中,當用戶未獲取正確的Token或者當Token失效時候,拋出403異常。
因此,我們需要修改Ng-Alain的403組件,當頁面加載時,使用TokenService
清空頁面Token,這樣的話,當用戶點擊返回首頁時,會自動返回至登錄頁面要求用戶重新登錄。組件403修改如下:
export class Exception403Component {
constructor(modalSrv: NzModalService
, @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,) {
modalSrv.closeAll();
this.tokenService.clear();
console.log('clear token done')
}
}
爲了驗證此問題,我們在後臺代碼中,設置Token過期時間爲1分鐘
JsonWebTokenUtility jsonWebTokenUtility = new JsonWebTokenUtility();
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, 1);
AuthTokenDetailsDTO authTokenDetailsDTO = AuthTokenDetailsDTO.builder()
.email(userName + "@test.com")
.userId(userName)
.expirationDate(calendar.getTime())
.roleNames(List.of("admin"))
.privileges(List.of("admin"))
.build();
String token = jsonWebTokenUtility.createJsonWebToken(authTokenDetailsDTO);
因此,當1分鐘Token失效之後,系統跳轉至403頁面
點擊返回首頁,系統重新跳轉至登錄頁面