How to add csrf token to angular 2 application

社会主义新天地 提交于 2019-12-23 16:03:59

问题


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.

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;
}

回答1:


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}.




回答2:


You may have CookieXSRFStrategy: Calling function 'CookieXSRFStrategy', function calls are not supported while using new CookieXSRFStrategy('myCookieName', 'My-Header-Name')} directly. Use a factory to avoid this error like below :

@NgModule({
 (...) 
    providers: 
    [
        { provide: XSRFStrategy, useFactory: xsrfFactory},
    ]
}) 
export class AppModule { }

export function xsrfFactory() {
    return new CookieXSRFStrategy('myCookieName', 'My-Header-Name');
}



回答3:


Can you read the cookie value(default "XSRF-TOKEN") in JavaScript by below?

document.cookie

(not developer tool.)

if it can't read,you maybe mistake how to set the cookie.

cookie path must be set root("/") like below.

cookie.setPath("/");



回答4:


In my case, the problem was on the back side (as correctly pointed out harufumi.abe) - my cookies came with a path /my-domain instead of /. After adding the setting on the backend (spring boot 2.0)

# Path of the session cookie.
server.servlet.session.cookie.path=/

everything began to work out of the box.



来源:https://stackoverflow.com/questions/39016862/how-to-add-csrf-token-to-angular-2-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!