我在我的应用程序中使用基于令牌的身份验证。我的后端是使用restful服务(spring)开发的。后端代码很好地生成了所需的访问令牌和带有时间线的刷新令牌,所以我用以下内容覆盖了http类:
export class customHttp extends Http {
headers: Headers = new Headers({ 'Something': 'Something' });
options1: RequestOptions = new RequestOptions({ headers: this.headers });
private refreshTokenUrl = AppSettings.REFRESH_TOKEN_URL;
constructor(backend: ConnectionBackend,
defaultOptions: RequestOptions,private refresh:OauthTokenService) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
console.log("custom http ");
return super.request(url, options)
.catch((err) => {
if (err.status === 401) {
console.log(" custome http 401 ");
// refresh the token
this.refresh.refresh().subscribe((tokenObj)=>{
console.log("tokenobj ");
})
} else {
console.log("err " + err);
}
}); } }
由于出现循环依赖错误,我陷入了刷新刷新()方法中的令牌的困境,因此我尝试在另一个模块中使用刷新服务,但没有成功。我正在使用与此中提到的相同的方法使用 rxjs 处理刷新令牌 https://stackoverflow.com/questions/34907151/handling-refresh-tokens-using-rxjs任何帮助都会很棒!
这对我有用:
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
//adding access token to each http request before calling super(..,..)
let token = this.authenticationService.token;
if (typeof url === 'string') {
if (!options) {
options = { headers: new Headers() };
}
options.headers.set('Authorization', `Bearer ${token}`);
}
else {
url.headers.set('Authorization', `Bearer ${token}`);
}
return super.request(url, options)
.catch((error) => {
//if got authorization error - try to update access token
if (error.status = 401) {
return this.authenticationService.updateToken()
.flatMap((result: boolean) => {
//if got new access token - retry request
if (result) {
return this.request(url, options);
}
//otherwise - throw error
else {
return Observable.throw(new Error('Can\'t refresh the token'));
}
})
}
else {
Observable.throw(error);
}
})
}
更新:authenticationService.updateToken() 实现应取决于您使用的授权提供程序/授权机制。就我而言,它是 OAuth Athorization Server,因此实现基本上将正文中带有刷新令牌的 post 请求发送到配置的令牌 url,并返回更新的访问和刷新令牌。 tokenEndPointUrl 由 OAuth 配置并发出访问和刷新令牌(取决于发送的 grant_type)。因为我需要刷新令牌,所以我将 grant_type 设置为刷新令牌。代码看起来类似于:
updateToken(): Observable<boolean> {
let body: string = 'refresh_token=' + this.refreshToken + '&grant_type=refresh_token';
return this.http.post(tokenEndPointUrl, body, this.options)
.map((response: Response) => {
var returnedBody: any = response.json();
if (typeof returnedBody.access_token !== 'undefined'){
localStorage.setItem(this.tokenKey, returnedBody.access_token);
localStorage.setItem(this.refreshTokenKey, returnedBody.refresh_token);
return true;
}
else {
return false;
}
})
}
希望能帮助到你
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)