我有2个令牌。 token_a持续很长时间,用于生成token_b。 token_b每15分钟到期一次。
用户可以导航到模块,但是在他们能够做到这一点之前我有一个警卫来检查token_b是否过期。但是,他们可能已经在模块内并进行不需要页面更改的api调用。我的理解是,警卫主要用于保护路线。
如何在发出http请求之前解决检查令牌是否已过期的问题。
api.service.ts
import { Injectable } from '@angular/core';
import { environment } from './../../../../environments/environment';
import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class ApiService {
constructor(
private http: HttpClient,
) { }
private setHeaders(): HttpHeaders {
const headersConfig = {
'Content-Type': 'application/json',
// 'Accept': 'application/json plain/text'
};
const token = localStorage.getItem('profile_token');
if (token) {
headersConfig['Authorization'] = 'Bearer ' + token;
}
return new HttpHeaders(headersConfig);
}
private formatErrors(error: any) {
console.log(error);
return Observable.throw(error);
}
get(path: string, httpParams: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), params: httpParams })
.catch(this.formatErrors)
.map((res) => res);
}
put(path: string, body: Object = {}): Observable<any> {
return this.http.put(
`${environment.api_url}${path}`,
JSON.stringify(body),
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res) => res);
}
post(path: string, body: Object = {}): Observable<any> {
return this.http.post(
`${environment.api_url}${path}`,
body,
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res) => res);
}
delete(path): Observable<any> {
return this.http.delete(
`${environment.api_url}${path}`,
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res) => res);
}
}
答案 0 :(得分:0)
据我所知,您应该将token_b生成时间保存在localstorage中,每次必须使用token_b时,请检查15分钟是否已过去。如果经过15分钟,则重新生成token_b并将新生成时间保存在localstorage中。
答案 1 :(得分:0)
您可以检查takeen是否有效,然后只提出请求,否则抛出错误。您可以参考以下代码:
import { Injectable } from '@angular/core';
import { environment } from './../../../../environments/environment';
import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class ApiService {
constructor(
private http: HttpClient,
) { }
...
get(path: string, httpParams: HttpParams = new HttpParams()): Observable<any> {
if(this.isTokenValid()) {
return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), params: httpParams })
.catch(this.formatErrors)
.map((res) => res);
} else {
return this.throwError();
}
}
...
throwError() {
return Observable.throw({message: 'Not authenticated'}});
}
isTokenValid() {
// logic to check token expiry return true false accordingly;
}
}