question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

HttpInterceptor (v1.0.0-beta.x), set custom (refresh) token in the same Authorization header

See original GitHub issue

I’m trying to use the new v1.0 beta version that uses a HttpInterceptor.

I need to use a refresh token to update the access token.

First, I tried to create a factory function as described in the README. I tried to use JwtHelper inside the TokenService that was injected in the factory function, following the instructions from the previous version to check if the token was expired and then to refresh it, using HttpClient.

But I had issues related to a cycling import, so I couldn’t use JwtHelper inside the TokenService. I also had issues using the HttpClient, but it seems there’s a workaround. I still couldn’t use the workaround as I had the problem with JwtHelper.

Then I tried to move that logic outside of that TokenService, and to start a simple prototype, just refreshing the token manually. But then, I have to use the refresh_token in the Authorization header instead of the access_token to be able to refresh the access_token, and no matter if I set it manually it is still overwritten by the HttpInterceptor.

This is my token refreshing code:

refreshToken() {
    const refreshToken = this.getRefreshToken();
    console.log(`refreshToken: ${refreshToken}`);
    if (refreshToken) {
      const preRequest = this.http.post(
        `${environment.host}/api/v2/login/refresh-token`,
        {},
        { headers: new HttpHeaders().set('Authorization', `Bearer ${refreshToken}`) }).subscribe(
          (result) => {
            console.log(result);
          },
        );
    }

But I can see and compare the console.loged token and the token used in the HTTP request header and the token being sent is the access_token, not the custom refresh_token.


Am I doing it wrong? Is there a way to achieve that? Or is there a way to use the JwtHelper and the HttpClient inside the TokenService that is injected in the factory function?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
tiangolocommented, Sep 30, 2017

@MilosStanic so, first, make sure you are using the beta README: https://github.com/auth0/angular2-jwt/tree/v1.0

I first tried to use a factory function and use the helper functions (but those are only documented in the master branch, although they exist in the v1.0 beta branch): https://github.com/auth0/angular2-jwt#using-jwthelper-in-components

But as the interceptor and the helpers live in the same NgModule, it is not possible to use the helpers inside the factory function. At least not easily.

You could actually do everything without this package by manually adding the Authorization header to each request, like:

...

this.http.get(
        `${environment.host}/api/v2/private`,
        { headers: new HttpHeaders().set('Authorization', `Bearer ${accessToken}`) }).subscribe...

...

The only thing this package does is that: add those headers to each request for some whitelistedDomains. That way, you don’t have to add headers like above but you can just use the HttpClient without worrying about authorization, like:

...

this.http.get(`${environment.host}/api/v2/private`).subscribe...

...


The problem is that most of the business logic goes into handling the refresh token. When to refresh, when and how to invalidate (log out) the tokens, how often to refresh the token and where to store the refresh and access tokens, etc.

So, here’s what I did:

  • Create a normal tokenGetter:
export function tokenGetter() {
  return localStorage.getItem('access_token');
}
  • Instantiate the module with that token getter and some whitelistedDomains (for testing):
...

JwtModule.forRoot({
      config: {
        whitelistedDomains: environment.whitelistedDomains,
        tokenGetter,
      },
    }),

...
  • Given that, at some point I add an access_token to localStorage, the above, using angular2-jwt will handle automatically sending the access token in each request.

…now, onto the hardest part, handling refresh tokens.

  • Then I create a service auth.service.ts.

  • In the Auth Service, I have a login function that sends a POST with the user credentials as JSON. After receiving the data, it stores the access token and refresh token in local storage AND in ngrx/store (a Redux-like global state management for Angular).

  • As ngrx/store is based in observables, I can subscribe to changes in the access token. There, I use the helpers from angular2-jwt to find out when the token is going to expire.

  • And then, I create an Observable that is delayed until 3 min before the access token expires and that requests a new access token using the refresh token. As the only place that I’m gonna use the refresh token is when I’m requesting a new access token, it is only one single point in the code where I’m using the refresh token, so I can just set the headers with the refresh token for that specific case, and for the rest of the endpoints in all the app, let the package add the access_token automatically from localStorage:

this.http.post(
        `${environment.host}/api/v2/login/refresh-token`,
        {},
        { headers: new HttpHeaders().set('Authorization', `Bearer ${refreshToken}`) }).subscribe...

I hope that helps you a bit finding out how to adapt it to your implementation.

0reactions
stale[bot]commented, Oct 26, 2019

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If you have not received a response for our team (apologies for the delay) and this is still a blocker, please reply with additional information or just a ping. Thank you for your contribution! 🙇‍♂️

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to implement automatic token insertion in requests using ...
The interceptor can help with a variety of tasks: using in authorization processes by adding a token for the request, changing headers, modifying...
Read more >
Issue with creating refresh token via HttpInterceptor
I am trying to implement refresh tokens in our application using the ... https://codinglatte.com/posts/angular/refreshing-authorization- ...
Read more >
OAuth 2.0 Authentication plugin - Kong Docs
An optional integer value telling the plugin how many seconds a token/refresh token pair is valid for, and can be used to generate...
Read more >
OAuth authorization - Pipedrive Developer Documentation
Authorization via OAuth is a well-known and stable way to get fine-grained access to an API. From requesting authorization to refreshing the tokens, ......
Read more >
OAuth with Zoom
Access tokens expire after one hour. Using an access token. Make requests to the Zoom API by sending the access_token as the Authorization...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found