Angular2 Spring身份验证

时间:2016-08-06 06:03:01

标签: spring angular

我有单独的Angular2 Client和Spring托管服务器。 我的Angular2应用程序可以调用spring的rest调用。 但是,我在使用Spring进行CSRF认证时遇到的困难很少。

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())


        }

听到什么都没发生。

如果你帮我打电话给春天,请提前谢谢。

1 个答案:

答案 0 :(得分:0)

我认为您可以使用RC2提供的Angular2的自动XSRF处理。这是由XSRFHandler类在幕后完成的,不需要将cookie显式添加到请求中。

请参阅以下链接: