如何使用角度2中的自定义http刷新访问令牌? [英] how to refresh the access token using custom http in angular 2?

查看:57
本文介绍了如何使用角度2中的自定义http刷新访问令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用基于令牌的身份验证。我的后端是使用restful service(spring)开发的。后端代码很好地生成了所需的访问令牌和刷新令牌的时间线,所以我已经覆盖了以下的http类:

I am using token based authentication in my application. My backend is developed using restful service(spring).The backend code is very well generating the required the access token and refresh tokens with timelines, So I have overidden the http class with following:

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处理刷新令牌相同的方法。任何帮助都会太棒了!

I am getting stuck in refreshing the token at refresh() method as I am getting cyclic dependency error so I tried to use refresh service in another module but no luck. I am using the same approach as mentioned in this Handling refresh tokens using rxjs Any help would be great!

推荐答案

这对我有用:

 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);
            }
        })
}

更新:身份验证Service.updateToken()实现应该依赖于您使用的授权提供程序/授权机制。在我的例子中它是OAuth Athorization Server,因此实现基本上将带有刷新令牌的post请求发送到配置的令牌url并返回更新的访问和刷新令牌。 tokenEndPointUrl由OAuth配置并发出访问和刷新令牌(取决于发送的grant_type)。因为我需要刷新令牌我将grant_type设置为refresh_token。代码类似于:

UPDATE: authenticationService.updateToken() implementation should depend on authorization provider/authorization mechanism you use. In my case it is OAuth Athorization Server, so implementation basically sends post request with refresh token in the body to configured token url and returns updated access and refresh tokens. tokenEndPointUrl is configured by OAuth and issues access and refresh tokens (depending on grant_type sent). Because i need to refresh token i set grant_type to refresh_token. Code looks similar to:

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;
        }
        })
}

希望有所帮助

这篇关于如何使用角度2中的自定义http刷新访问令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆