2

I am creating an SPA using Angular 6 for front end and Adonisjs for backend.

And now I got stuck in the problem csrf. If I disable csrf in adonis/config/shield.js I have complete my task. But, I don't want to disable csrf.

I have followed some suggestions on internet about using Angular HttpInterceptor but still not work.

here is csrf config in shield.js

csrf: {
enable: true,
methods: ['POST', 'PUT', 'DELETE'],
filterUris: ['/api/auth/signin'],
cookieOptions: {
  httpOnly: false,
  sameSite: true,
  path: '/',
  maxAge: 7200
}
// compareHostAndOrigin: true}

And here is my token-interceptor.service.ts

    import { Injectable } from '@angular/core';
import {
  HttpClientXsrfModule,
  HttpInterceptor,
  HttpXsrfTokenExtractor,
  HttpRequest,
  HttpHandler,
  HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class TokenInterceptorService implements HttpInterceptor {
  constructor(private tokenExtractor: HttpXsrfTokenExtractor) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const headerName = 'XSRF-TOKEN';
    const respHeaderName = 'X-XSRF-TOKEN';
    const token = this.tokenExtractor.getToken() as string;
    if (token !== null && !req.headers.has(headerName)) {
      req = req.clone({ headers: req.headers.set(respHeaderName, token) });
    }
    return next.handle(req);

  }
}

And I don't know if the Angular intercept the Http. because from my request, I don't see any X-XSRF-TOKEN header.

And I still confuse about the token Adonisjs uses. because when I log in and console.log(request.csrfToken) I got a value but the value is different from token in database (I use mongoDB).

Should I got csrf from the beginning I open my app? or something else?

Please suggest me how to fix it.

Sulaiman Triarjo
  • 333
  • 3
  • 15
  • You don't need the csrf in your angular client application, you need to enable a jwt or api security middleware – Pepe Nov 15 '18 at 18:02

0 Answers0