Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add csrf token to angular 2 application

I have enabled the CSRF in the java back-end (in SecurityConfig.java file) due to maintain user sessions between the angular2 and spring app. but when the post submission fired, I haven't seen any CSRF token binded to the POST request.

enter image description here

How would be possible way to add the CSRF token to my angular2 app. (add to the post request )


loginService.ts

  userLogin(loginDTO){
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    var result = this._http.post(this._rest_service_login, JSON.stringify(loginDTO),options)
        .map(res => res.json());
    return result;
}
like image 895
Sadun89 Avatar asked Jan 06 '23 12:01

Sadun89


1 Answers

You should have a look at the developer guide of Angular2. You can implement a strategy (or use an existing one) by using providers.

RC.5

@NgModule({
 (...) 
    providers: 
    [
        { provide: XSRFStrategy, useValue: new CookieXSRFStrategy('myCookieName', 'My-Header-Name')},
    ]
}) 
export class AppModule { }

RC.4

bootstrap(
    AppComponent,
    [
        { provide: XSRFStrategy, useValue: new CookieXSRFStrategy('myCookieName', 'My-Header-Name')},
    ]
);

You can also implement a custom strategy for your application by using the following provider { provide: XSRFStrategy, useClass: MyXSRFStrategy}.

like image 195
Nicolas Henneaux Avatar answered Jan 13 '23 15:01

Nicolas Henneaux