在Angular 2中设置Authorization标头

时间:2016-11-10 14:06:37

标签: java spring angular angular2-http

我正在开发Spring中的restful服务,我已经实现了Json Web Token(JWT)进行身份验证和授权。登录后,将正确的身份验证令牌返回给请求用户。在每个请求中,我正在检查请求标头中的令牌并验证令牌。过滤器代码如下。

    let token = "";
    if (undefined != this._tokenService.getToken()) {
        token = this._tokenService.getToken().getToken()
    }
    let header: Headers = new Headers();
    header.append('Content-Type', 'application/json');
    header.append('Authorization', token);
    let options = new RequestOptions({headers: header});

    return this.http.get(url, options)
       .map(res => {
          console.log(res.status)
          if (res.status == 200) {
              return res.json();
          } else if (res.status == 401) {
              return null;
          } else {
              throw new Error('This request has failed ' + res.status);
           }
        });

我使用角度2作为前端框架。现在,在获得身份验证令牌后,我使用" POSTMAN "来请求安全资源。它工作得很好,并且在过滤器中接收到令牌,一切顺利。我在"授权"中设置令牌。头。 现在的问题是当我做同样的事情时使用角度2令牌在过滤器中变为null但是firebug显示"授权"标头已设置并成功发送。我这样做

{{1}}

我做错了什么?在角度2中设置标题的正确方法是什么?如何解决此问题?

3 个答案:

答案 0 :(得分:2)

如果你想要一个更持久的解决方案,我有一个适合你。

通过继承angular的http服务,您可以注入子类型,然后总是添加标题。

player_equipment

然后在你的模块中

import {
  Http,
  ConnectionBackend,
  Headers,
  Request,
  RequestOptions,
  RequestOptionsArgs,
  Response,
  RequestMethod,
} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';

// A service that can get the logged in users jwt token as an observable
import { SecurityService } from './security.service';

// A service that handles cookies (angular2-cookie)
import { CookieService } from '../cookie';

/**
 * Custom Http client that handles conversions to json, adds CSRF token, and jwt token and redirects to signin if token is missing
 */
export class SecureHttp extends Http {

  constructor(
    backend: ConnectionBackend,
    defaultOptions: RequestOptions,
    private securityService: SecurityService,
    private cookieService: CookieService
  ) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<any> {
    if (typeof url === 'string') {
      return this.get(url, options); // Recursion: transform url from String to Request
    }

    return this.sendRequest(url, options);
  }

  get(url: string, options?: RequestOptionsArgs): Observable<any> {
    return this.sendRequest({ method: RequestMethod.Get, url: url, body: '' }, options);
  }

  post(url: string, body: string, options?: RequestOptionsArgs): Observable<any> {
    return this.sendRequest({ method: RequestMethod.Post, url: url, body: body }, options);
  }

  put(url: string, body: string, options?: RequestOptionsArgs): Observable<any> {
    return this.sendRequest({ method: RequestMethod.Put, url: url, body: body }, options);
  }

  delete(url: string, options?: RequestOptionsArgs): Observable<any> {
    return this.sendRequest({ method: RequestMethod.Delete, url: url, body: '' }, options);
  }

  patch(url: string, body: string, options?: RequestOptionsArgs): Observable<any> {
    return this.sendRequest({ method: RequestMethod.Patch, url: url, body: body }, options);
  }

  head(url: string, options?: RequestOptionsArgs): Observable<any> {
    return this.sendRequest({ method: RequestMethod.Head, url: url, body: '' }, options);
  }

  private sendRequest(requestOptionsArgs: RequestOptionsArgs, options?: RequestOptionsArgs): Observable<any> {

    let requestOptions = new RequestOptions(requestOptionsArgs);

    // Convert body to stringified json if it's not a string already
    if (typeof requestOptions.body !== 'string') {
      requestOptions.body = JSON.stringify(requestOptions.body);
    }

    // Get xsrf token from spring security cookie
    // by adding .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    const csrfToken: string = this.cookieService.get('XSRF-TOKEN');

    let baseOptions: RequestOptions = new RequestOptions({
      headers: new Headers({
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'X-XSRF-TOKEN': csrfToken
      })
    });

    return this.securityService.accessToken$.mergeMap(token => {

      // If there is a token we add it to the baseOptions
      if (token) {
        baseOptions.headers.set('Authorization', 'Bearer ' + token);
      }

      // We create a request from the passed in method, url, body and merge our base options in there
      let request = new Request(baseOptions.merge(requestOptions));

      return super.request(request, options)
        .map(res => res.json())
        .catch(this.errorHandler);
    });
  }

  private errorHandler(errorResponse: Response): Observable<any> | ErrorObservable {
    if (errorResponse.status === 401) {
      console.log('redirecting to login');
      window.location.href = '/login';
      return Observable.empty();
    }

    // If it's a serious problem we can log it to a service if we want to
    if (errorResponse.status === 500) {
      // this.errorReporter.logError(errorResponse);
    }

    console.error(errorResponse);

    return Observable.throw(errorResponse.text().length > 0 ? errorResponse.json() : { status: 'error' });
  }
}

答案 1 :(得分:0)

将Bearer添加到您的auth标头,内容类型标题也像:

headers.append("content-type", "application/x-www-form-urlencode");
 headers.append("Authorization", "Bearer " + this.accessToken);

答案 2 :(得分:0)

我采用了替代方法。 在URL和过滤器中附加令牌我正在拆分此令牌并将其用于身份验证。还可以使用请求包装器类并发送原始URL以进行进一步操作。 https://www.ibm.com/support/knowledgecenter/en/SSEP7X_7.0.4/com.ibm.wmqfte.doc/web_admin_servlet_filters.htm