在 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页面
点击返回首页,系统重新跳转至登录页面