如何将json Web令牌添加到每个标头?

Mor*_*n G 8 json jwt json-web-token angular2-services angular

因此,我尝试使用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']);
            }
        );

    }
Run Code Online (Sandbox Code Playgroud)

和我的login.service

authenticate(form_body){
        return this.http.post('/login', JSON.stringify(form_body), {headers: headers})
                .map((response => response.json()));
    }
Run Code Online (Sandbox Code Playgroud)

我知道这些并不是真的需要,但也许它会有所帮助!一旦这个令牌被创建并存储它,我想做两件事,在标题中发送它并提取我用它放入的过期日期.

一些Node.js登录代码

var jwt = require('jsonwebtoken');
function createToken(user) {
  return jwt.sign(user, "SUPER-SECRET", { expiresIn: 60*5 });
}
Run Code Online (Sandbox Code Playgroud)

现在我只是尝试通过角度服务将其传递回使用此服务的节点.

getUsers(jwt){
        headers.append('Authorization', jwt);
        return this.http.get('/api/users/', {headers: headers})
            .map((response => response.json().data));
    }
Run Code Online (Sandbox Code Playgroud)

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"' }
Run Code Online (Sandbox Code Playgroud)

Ado*_*ogo 14

创建自定义http类并覆盖request在每个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);
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,我们需要配置我们的主模块,以便为我们的自定义http类提供XHRBackend.在主模块声明中,将以下内容添加到providers数组:

app.module.ts

import { HttpModule, RequestOptions, 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 ]
})
Run Code Online (Sandbox Code Playgroud)

之后,您现在可以在服务中使用自定义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();
    } );
  }
}
Run Code Online (Sandbox Code Playgroud)

资源


Thi*_*ier 7

我看到几个选项可以为每个请求透明地设置标头:

  • 实现HttpClient服务而不是默认的Http服务.
  • 提供自己的RequestOptions类实现
  • 它自己覆盖Http类

这样你就可以在一个地方设置标题,这会影响你的HTTP调用.

请参阅以下问题: