因此,我正在尝试使用
JSON Web令牌进行身份验证,并且正在努力弄清楚如何将它们附加到标头并根据请求发送它们.
我试图使用https://github.com/auth0/angular2-jwt,但我无法使用Angular并放弃,并认为我可以弄清楚如何在每个请求中发送JWT或在头部(最好是标头)中发送它.它比我想象的要困难一点.
这是我的登录
submitLogin(username,password){ console.log(username); console.log(password); let body = {username,password}; this._loginService.authenticate(body).subscribe( response => { console.log(response); localStorage.setItem('jwt',response); this.router.navigate(['UserList']); } ); }
和我的login.service
authenticate(form_body){ return this.http.post('/login',JSON.stringify(form_body),{headers: headers}) .map((response => response.json())); }
我知道这些并不是真的需要,但也许它会有所帮助!一旦这个令牌被创建并存储它,我想做两件事,在标题中发送它并提取我用它放入的过期日期.
var jwt = require('jsonwebtoken'); function createToken(user) { return jwt.sign(user,"SUPER-SECRET",{ expiresIn: 60*5 }); }
现在我只是尝试通过角度服务将其传递回使用此服务的节点.
getUsers(jwt){ headers.append('Authorization',jwt); return this.http.get('/api/users/',{headers: headers}) .map((response => response.json().data)); }
JWT是我在本地存储中的webtoken,我通过我的组件传递给服务.
我在任何地方都没有错误,但当它到达我的节点服务器时,我从未在标题中收到它.
'content-type': 'application/json',accept: '*/*',referer: 'http://localhost:3000/','accept-encoding': 'gzip,deflate,sdch','accept-language': 'en-US,en;q=0.8',cookie: 'connect.sid=s%3Alh2I8i7DIugrasdfatcPEEybzK8ZJla92IUvt.aTUQ9U17MBLLfZlEET9E1gXySRQYvjOE157DZuAC15I','if-none-match': 'W/"38b-jS9aafagadfasdhnN17vamSnTYDT6TvQ"' }
解决方法
创建自定义http类并覆盖请求方法以在每个http请求中添加令牌.
http.service.ts
import {Injectable} from '@angular/core'; import {Http,XHRBackend,RequestOptions,Request,RequestOptionsArgs,Response,Headers} from '@angular/http'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; @Injectable() export class HttpService extends Http { constructor (backend: XHRBackend,options: RequestOptions) { let token = localStorage.getItem('auth_token'); // your custom token getter function here options.headers.set('Authorization',`Bearer ${token}`); super(backend,options); } request(url: string|Request,options?: RequestOptionsArgs): Observable<Response> { let token = localStorage.getItem('auth_token'); if (typeof url === 'string') { // meaning we have to add the token to the options,not in url if (!options) { // let's make option object options = {headers: new Headers()}; } options.headers.set('Authorization',`Bearer ${token}`); } else { // we have to add the token to the url object url.headers.set('Authorization',`Bearer ${token}`); } return super.request(url,options).catch(this.catchAuthError(this)); } private catchAuthError (self: HttpService) { // we have to pass HttpService's own instance here as `self` return (res: Response) => { console.log(res); if (res.status === 401 || res.status === 403) { // if not authenticated console.log(res); } return Observable.throw(res); }; } }
现在,我们需要配置我们的主模块,以便为我们的自定义http类提供XHRBackend.在主模块声明中,将以下内容添加到providers数组:
app.module.ts
import { HttpModule,XHRBackend } from '@angular/http'; import { HttpService } from './services/http.service'; ... @NgModule({ imports: [..],providers: [ { provide: HttpService,useFactory: (backend: XHRBackend,options: RequestOptions) => { return new HttpService(backend,options); },deps: [XHRBackend,RequestOptions] } ],bootstrap: [ AppComponent ] })
之后,您现在可以在服务中使用自定义http提供程序.例如:
user.service.ts
import { Injectable } from '@angular/core'; import {HttpService} from './http.service'; @Injectable() class UserService { constructor (private http: HttpService) {} // token will added automatically to get request header getUser (id: number) { return this.http.get(`/users/${id}`).map((res) => { return res.json(); } ); } }