angular 使用jwt token验证

/**
 * Created by 何欣澄 on 2017/5/28 0028.
 */
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';
import {
  Http,
  RequestOptionsArgs,
  RequestOptions,
  Response,
  Headers
} from '@angular/http';

const mergeToken = (options: RequestOptionsArgs = {}) => { ①
  const newOptions = new RequestOptions({}).merge(options);
  const newHeaders = new Headers(newOptions.headers);
  const jwt = localStorage.getItem('jwt');
  if (jwt) {
    newHeaders.set('authorization', `Bearer ${jwt}`);
  }
  newOptions.headers = newHeaders;
  return newOptions;
};

@Injectable() ②
export class MyHttp {

  constructor(private http: Http) { ③
  }

  get(url: string, options?: RequestOptionsArgs): Observable { ④
    return this.http.get(url, mergeToken(options));
  }

  post(url: string, body: any, options?: RequestOptionsArgs): Observable {
    return this.http.post(url, body, mergeToken(options));
  }

  put(url: string, body: any, options?: RequestOptionsArgs): Observable {
    return this.http.put(url, body, mergeToken(options));
  }

  delete(url: string, options?: RequestOptionsArgs): Observable {
    return this.http.delete(url, mergeToken(options));
  }

  patch(url: string, body: any, options?: RequestOptionsArgs): Observable {
    return this.http.patch(url, body, mergeToken(options));
  }

  head(url: string, options?: RequestOptionsArgs): Observable {
    return this.http.head(url, mergeToken(options));
  }

}

① 写一个常量function 将token放在http header的authorization 中
② 依赖注入
③ 引入 angular 的http 服务
④ 封装各类动词的方法在每种请求中都加入 token

之后的所有请求后端都只需要使用自己封装号的这个MyHttp 服务就可以了。

当然登录时需要将token放在localStorage中,注销的时候需要将token移除

你可能感兴趣的:(angular(4+))