3

I'm a new web developer, working with spring boot and angular 8. When I try to login with the username and password the server generate a token and send it back to the http response, so my question is how to get the value of the cookie and store it in the browser.this is the java code that store the cookie in the header.

this is the response header where the token is.

Williamz007
  • 31
  • 1
  • 5
  • Please embed any code or images to your post here without linking out to other sites – Rod May 11 '20 at 20:44

1 Answers1

2

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)

Florian Ludewig
  • 4,338
  • 11
  • 71
  • 137
  • So when a user login the APIs must return to the web app accessToken also ? Somthing like that... public ResponseEntity> login(@requestBody LoginRequest loginRequest) { // some code... return new ResponseEntity<>(jwt, HttpStatus.OK); } – Williamz007 May 19 '20 at 14:37
  • 1
    yes, and you have to set the refresh token as a cookie – Florian Ludewig May 19 '20 at 15:43