احراز هویت و اعتبارسنجی کاربران در برنامههای Angular - قسمت چهارم - به روز رسانی خودکار توکنها
نویسنده: وحید نصیری
تاریخ: ۱۳۹۶/۰۹/۲۸ ۸:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
getAccessTokenExpirationDateUtc(): Date {
const decoded = this.getDecodedAccessToken();
if (decoded.exp === undefined) {
return null;
}
const date = new Date(0); // The 0 sets the date to the epoch
date.setUTCSeconds(decoded.exp);
return date;
} private refreshTokenSubscription: Subscription;
scheduleRefreshToken() {
if (!this.isLoggedIn()) {
return;
}
this.unscheduleRefreshToken();
const expiresAtUtc = this.getAccessTokenExpirationDateUtc().valueOf();
const nowUtc = new Date().valueOf();
const initialDelay = Math.max(1, expiresAtUtc - nowUtc);
console.log("Initial scheduleRefreshToken Delay(ms)", initialDelay);
const timerSource$ = Observable.timer(initialDelay);
this.refreshTokenSubscription = timerSource$.subscribe(() => {
this.refreshToken();
});
}
unscheduleRefreshToken() {
if (this.refreshTokenSubscription) {
this.refreshTokenSubscription.unsubscribe();
}
} refreshToken() {
const headers = new HttpHeaders({ "Content-Type": "application/json" });
const model = { refreshToken: this.getRawAuthToken(AuthTokenType.RefreshToken) };
return this.http
.post(`${this.appConfig.apiEndpoint}/${this.appConfig.refreshTokenPath}`, model, { headers: headers })
.finally(() => {
this.scheduleRefreshToken();
})
.map(response => response || {})
.catch((error: HttpErrorResponse) => Observable.throw(error))
.subscribe(result => {
console.log("RefreshToken Result", result);
this.setLoginSession(result);
});
} constructor(
@Inject(APP_CONFIG) private appConfig: IAppConfig,
private browserStorageService: BrowserStorageService,
private http: HttpClient,
private router: Router
) {
this.updateStatusOnPageRefresh();
this.scheduleRefreshToken();
} this.setLoginSession(response); this.scheduleRefreshToken();
this.deleteAuthTokens(); this.unscheduleRefreshToken();
"BearerTokens": {
"Key": "This is my shared key, not so secret, secret!",
"Issuer": "http://localhost/",
"Audience": "Any",
"AccessTokenExpirationMinutes": 2,
"RefreshTokenExpirationMinutes": 60
} ...
.post(`${this.appConfig.apiEndpoint}/${this.appConfig.refreshTokenPath}`, model, { headers: headers })
.finally(() => {
this.scheduleRefreshToken();
})
... ... const initialDelay = Math.max(1, expiresAtUtc - nowUtc); //return 1 ...
scheduleRefreshToken() {
if (!this.isLoggedIn()) {
return;
} «... و توکن فعلی را نامعتبر کند ...»
«... تمامی توکنهای شخص حذف میشوند ...»
cfg.TokenValidationParameters = new TokenValidationParameters
{
//...
//ClockSkew = TimeSpan.Zero
ClockSkew = TimeSpan.FromMinutes(5)
} this.http
.post<Xyz>(`${this.apiUrl}`, data, { withCredentials: true /* For CORS */ })
.map(response => response || {})
.catch(this.handleError); @Injectable()
export class CORSInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
withCredentials: true
});
return next.handle(request);
}
} app.UseCors(builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
//.AllowAnyOrigin()
.SetIsOriginAllowed((host) => true)
.AllowCredentials()
); services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:4200")
.AllowCredentials()
.Build());
}); app.UseCors("CorsPolicy");