所以我正在使用Angular 6构建一个Web应用程序,并使用SocialLogin库实现了Google登录。 这是我的代码:
public socialSignIn(socialPlatform : string) {
let socialPlatformProvider;
if(socialPlatform == "facebook"){
socialPlatformProvider = FacebookLoginProvider.PROVIDER_ID;
}else if(socialPlatform == "google"){
socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;
}
this.socialAuthService.signIn(socialPlatformProvider).then(
(userData) => {
let user: User = new User();
let newuserrequest: NewUserRequest = new NewUserRequest();
user.email = userData.email;
var username;
username = userData.name;
var uuid = this.newGuid();
newuserrequest.requestId = uuid;
newuserrequest.user = user;
newuserrequest.accountId = userData.id;
newuserrequest.accountIdToken = userData.idToken;
this.newuserrequest = Array<NewUserRequest>(newuserrequest);
this.personname2 = userData.name;
this.personname = this.personname2.toString();
console.log('Personname: ' + this.personname);
this.div = document.getElementById("name");
this.div.textContent = this.personname;
var token;
token = userData.idToken;
this.saveValueUser(username, user.email);
this.islogedin = true;
this.saveValue(token);
this.communicator = new CommunicatorService(this.httpClient);
var url;
url = "myurl/newuser";
this.communicator.getDataFromServer(this.newuserrequest, url)
.subscribe(
(data:any) => {
console.log(data);
}
);
}
);
}
此代码工作正常,但仅 1 小时。使用 JWT-helper-service,我创建了一个方法,让我知道我的令牌是否仍然有效以及它的有效期。这是方法:
private tokenHandler(){
this.helper = new JwtHelperService();
this.isExpired = this.helper.isTokenExpired(this.token);
if(this.isExpired != true) {
this.expirationDate = this.helper.getTokenExpirationDate(this.token);
}
console.log("Is expired: " + this.isExpired);
console.log("Expiration date: " + this.expirationDate);
if(this.isExpired == true){
this.signOut();
}
}
如何在令牌过期之前刷新令牌?
您可以在首次获取令牌后在代码中实现计划调用,以设置倒数计时器并在到期前的特定时间触发续订。
查看此链接 https://auth0.com/docs/quickstart/spa/angular2/05-token-renewal
示例这是特定于AuthO库的,但您可以轻松地将其适应令牌检索库。
此外,该示例面向角度 2,因此请记住 rxjs 进行了一些更改(例如,现在我们只使用 of(( 等代替 observable.of(( 等(。
如果您需要更多帮助,请告诉我。