如何向每个标头添加 json Web 令牌? [英] How do I add a json web token to each header?

查看:23
本文介绍了如何向每个标头添加 json Web 令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试使用 JSON Web 令牌进行身份验证,并且正在努力弄清楚如何将它们附加到标头并在请求时发送它们.

So I am trying to use JSON web tokens for authentication and am struggling trying to figure out how to attach them to a header and send them on a request.

我试图使用 https://github.com/auth0/angular2-jwt但我无法让它与 Angular 一起工作并放弃了,并认为我可以弄清楚如何在每个请求中发送 JWT 或在标头(最好是标头)中发送它.只是比我想象的要难一些.

I was trying to use https://github.com/auth0/angular2-jwt but I could not get it working with Angular and gave up, and figured I could just figure out how to either send the JWT in every request or send it in the header(preferably the header). It's just been a little bit harder than I thought it would be.

这是我的登录信息

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

and my login.service

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

我知道这些并不是真正需要的,但也许会有所帮助!创建此令牌并存储它后,我想做两件事,将它发送到标头中并提取我在其中输入的到期日期.

I know these are not really needed but maybe it'd help! Once this token gets created and I store it, I would like to do 2 things, send it in the header and extract the expiration date that I put in with this.

一些 Node.js 登录代码

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

现在我只是想通过 angular 服务将它传递回具有此服务的节点.

Now I am just trying to pass it via an angular service back to node with this service.

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

JWT 是我在本地存储中的网络令牌,我通过我的组件传递给服务.

JWT is my webtoken in local storage that I pass through my component to the service.

我在任何地方都没有收到错误,但是当它到达我的节点服务器时,我从未在标头中收到它.

I get no errors anywhere but when it gets to my node server I never receive it in the header.

'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 类并覆盖 request 方法以在每个 http 请求中添加令牌.

Create custom http class and override the request method to add the token in every http request.

http.service.ts

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 数组中:

Now, we need to configure our main module to provide the XHRBackend to our custom http class. In your main module declaration, add the following to the providers array:

app.module.ts

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 ]
})

之后,您现在可以在您的服务中使用您的自定义 http 提供程序.例如:

After that, you can now use your custom http provider in your services. For example:

user.service.ts

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

来源

这篇关于如何向每个标头添加 json Web 令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆