【问题标题】:How do I add a json web token to each header?如何向每个标头添加 json Web 令牌?
【发布时间】:2016-05-24 08:46:51
【问题描述】:

所以我正在尝试使用 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()));
    }

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

一些 Node.js 登录代码

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"' }

【问题讨论】:

  • 是的..来自 auth0 的 angular2-jwt 写得不好...也无法工作

标签: json angular jwt json-web-token angular2-services


【解决方案1】:

创建自定义 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);
    };
  }
}

现在,我们需要配置我们的主模块,为我们的自定义 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 ]
})

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

Source

【讨论】:

    【解决方案2】:

    这是一个来自 Angular 代码的示例,例如,您可以这样编写,

     $scope.getPlans = function(){
        $http({
          url: '/api/plans',
          method: 'get',
          headers:{
            'x-access-token': $rootScope.token
          }
        }).then(function(response){
          $scope.plans = response.data;
        });
      }
    

    在你的服务器上,你可以这样做,

    var jwt    = require('jsonwebtoken'); // used to create, sign, and verify tokens
    var config = require('./config'); // get our config file
    
    var secret = {superSecret: config.secret}; // secret variable
    
    // route middleware to verify a token. This code will be put in routes before the route code is executed.
    PlansController.use(function(req, res, next) {
    
      // check header or url parameters or post parameters for token
      var token = req.body.token || req.query.token || req.headers['x-access-token'];
    
      // If token is there, then decode token
      if (token) {
    
        // verifies secret and checks exp
        jwt.verify(token, secret.superSecret, function(err, decoded) {
          if (err) {
            return res.json({ success: false, message: 'Failed to authenticate token.' });
          } else {
            // if everything is good, save to incoming request for use in other routes
            req.decoded = decoded;
            next();
          }
        });
    
      } else {
    
        // if there is no token
        // return an error
        return res.status(403).send({
            success: false,
            message: 'No token provided.'
        });
    
      }
    });
    
    // Routes
    PlansController.get('/', function(req, res){
      Plan.find({}, function(err, plans){
      res.json(plans);
      });
    });
    

    如果你还不清楚,可以在这里查看我的博文Node API Authentication with JSON Web Tokens - the right way的详细信息。

    【讨论】:

      【解决方案3】:

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

      • 实现一个 HttpClient 服务来代替默认的 Http 服务。
      • 提供您自己的 RequestOptions 类实现
      • 重写自身的 Http 类

      这样您可以将您的标头设置在一个地方,这会影响您的 HTTP 调用。

      查看以下问题:

      【讨论】:

      • 太棒了!如果您想拦截每个 HTTP 请求,这非常有用。
      • 非常感谢!!非常感谢您花时间回答所有这些 angular2 问题,当我遇到困难时,有一半的时间我的谷歌搜索会引导我找到您的答案!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多