Search code examples
javascriptangular2-routingcsrf

How can i send a CSRF Token


I am trying to sending login details but response error is showing csrf token is missing. How can i send a csrf token from angular 2
to backend Django.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Cookie } from 'ng2-cookies'; 
import  'rxjs/add/operator/map';

@Injectable()
export class AuthenticationService {
    constructor(private http: HttpClient){}

    login(username:string,password:string){
        return this.http.post<any>('/api/auth',{username:username,password:password},)
            .map(user => {
                //login successful if there a jwt token in the response
                if(user && user.token){
                    localStorage.setItem('currentUser',JSON.stringify(user));
                }
                return user;
            })
    }

    logout(){
        //remove user from local storage to log user out 
        localStorage.removeItem('CurrentUser');
    }
}

Solution

  • Both backend and frontend have to work together on this. When CSRF is enabled on the backend by any means, it basically means that each request is supposed to send a unique (not exactly unique, more on this later) identifier via a HTTP header in each HTTP request to the server side.

    So the client side (angular in this case) has to know the name of the HTTP header and has to set the value of that header.

    The value of this HTTP header (or a valid CSRF token) is the tricky part. Typically to set it, client side keeps on calling server side /csrf kind of API with valid credentials to fetch this value and set it in a global variable (all such /csrf calls usually go on periodic intervals, say 15-30 seconds. The implementation of uniqueness is left up to the server). OR for simplicity, the CSRF token value is set only once at the the login time of the user, and is kept on the client side for that whole session.

    This CSRF token then is sent as the value of the HTTP header with each HTTP request from client side. The server validates the CSRF token by reading that header and lets the HTTP request go through.

    Please note that all of the above can also be implemented via a cookie instead of a HTTP header.

    Action items:

    1. Work with your backend team to know the HTTP header name for the CSRF token and the strategy to set its value. OR check whether it is set in any cookie if not a HTTP header.

    2. See how it can be set via angular js in a standardized way at: Django csrf token + Angularjs and AngularJS + Django Rest Framework + CORS ( CSRF Cookie not showing up in client ) (Django) and How to add csrf token to angular 2 application (Spring)

    3. Read more about CSRF at: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) and at https://dzone.com/articles/cross-site-request-forgery