Get the value of (Set-Cookie) and store it in the browser angular 8

Viewed 1473
1 Answers

Settings cookies needs to be handled on the server side and since you are seeing the Set-Cookie header in the HTTP request everything seems to be fine. (You can also check it by navigating to the Application tab in the Chrome Dev Tools and then select Cookies on the left panel)

Generally, you shouldn't "get" the access token from the cookies inside your client (Angular) application, because of security reasons. However this depends on your token strategy (for example it is ok to get the access token into you angular application when you use a refresh token to fetch the access token)

Long story short, you should checkout this really comprehensive article about handling JWTs on frontend clients. It covers everything you need to know.

You can also check out this great video by Ben Awad


The simplified version goes like this:

  1. User signs in
  2. If sign in is valid, server responds with a refresh token (as a cookie) and an access token (just in the response payload)
  3. Access token is stored in a javascript variable (in memory) or in localStorage

The client is now authenticated

  1. User makes request to access a resource, that requires authentication. Now the client will send the access token as an Http header (if you're using Angular you would use an auth token interceptor for this). And the refresh token is sent automatically to the server (since it is stored in the cookies). Here is what might happen:
    • Access token is valid: user is still authenticated, send protected resource
    • Acess token is invalid / expired: use the refresh token to generate a new access token, send protected resources
    • Refresh token is also invalid: user is not authenticated

An implementation for the AuthTokenInterceptor in Angular might look like this (obviously this is missing some code snippets, but it outlines the general idea):

import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpErrorResponse,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class AuthTokenInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // get access token
    const accessToken = this.authService.accessToken;

    // set http header with token
    const setHeaders = { ['Authentication']: `Bearer ${accessToken}` };
    req = req.clone({ setHeaders, withCredentials: true });

    // execute the http request
    return next.handle(req).pipe(
      catchError(async (error) => {
        console.log("error in intercetpor", error);
        // try to refresh the access token if the request fails with a 401 error
        if (
          error instanceof HttpErrorResponse &&
          error.status === 401
        ) {
          const newAccessToken = await this.authService.refreshAccessToken()

          // set http header with new token
          const setNewHeaders = { ['Authentication']: `Bearer ${newAccessToken}` };
          req = req.clone({ setNewHeaders, withCredentials: true });

          return next.handle(req);
        }

        // unexpected error
        return throwError(error);
      })
    );
  }
}

You can find a working implementation that I use in one of my projects here. But its always difficult to understand what is going on in a foreign codebase. Thus I would recommend following the article above. (it is more important to understand the concept, the implementation might vary from project to project)

Related