简体   繁体   中英

Angular2 Spring Authentication

I have separate Angular2 Client and Spring hosted servers. My Angular2 application is able to call rest call of the spring. But, I am facing few difficulties to do CSRF authentication with Spring.

main.ts:

    import { CsrfBaseRequestOptions } from './app/shared';

    bootstrap(AppComponent, [
      ROUTER_PROVIDERS,
      HTTP_PROVIDERS,
      ...
      provide(RequestOptions, { useClass: CsrfBaseRequestOptions })
    ]);
    XhrBaseRequestOptions:

    @Injectable()
    export class XhrBaseRequestOptions extends BaseRequestOptions {

      constructor() {
        super();

        this.headers.append('X-Requested-With', 'XMLHttpRequest');
      }

    }
    CsrfBaseRequestOptions:

    import { Injectable } from '@angular/core';
    import { XhrBaseRequestOptions } from './xhr-base-request-options';

    @Injectable()
    export class CsrfBaseRequestOptions extends XhrBaseRequestOptions {

      constructor() {
        super();

        let csrfToken = this.getCsrfToken('X-CSRF-TOKEN');
        if (csrfToken) {
          this.headers.append('X-CSRF-TOKEN', csrfToken);
        }
      }

      getCsrfToken(tokenName:string):string {
        let tokenNameEQ = tokenName + '=';
        let ck = document.cookie;
        let ca = ck.split(';');

        for (let i = 0; i < ca.length; i++) {
          let c = ca[i];
          while (c.charAt(0) === ' ') c = c.substring(1, c.length);
          if (c.indexOf(tokenNameEQ) === 0) return c.substring(tokenNameEQ.length, c.length);
        }
        return null;
      }

    }

    index.ts

    onSubmit(event, username, password) {
            this.headers = new Headers();
            this.headers.append("Content-Type", 'application/json');
            let body = JSON.stringify({username, password});
            this.http.post('http://localhost:8080/EEP/test', body, { headers: this.headers })
                .subscribe((res) => this.token = res.json())


        }

hear Nothing is happening.

THanks in advance if you help me to call the Spring ..

I think that you could use the Automatic XSRF handling of Angular2 available from RC2. This is done under the hood by the XSRFHandler class and don't need to add explicitly the cookie to the request.

See these links:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM