How do I add a json web token to each header?

北城以北 提交于 2019-12-04 11:15:56

问题


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.

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.

Here is my Login

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

    }

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.

Some of the Node.js login code

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

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

回答1:


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

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

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

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

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

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:


I see several options to set an header transparently for each request:

  • Implement an HttpClient service to use instead of the default Http one.
  • Provide your own implementation of the RequestOptions class
  • Override the Http class it self

This way you could set your header in one place and this would impact aok your HTTP calls.

See the following questions:

  • How to set default HTTP header in Angular2?
  • Angular2 - set headers for every request
  • How do you set global custom headers in Angular2?



回答3:


Here is an example from Angular code to get plans for instance, you just write it like this,

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

and on your server, you can do this,

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

If you are still not clear, you can check out the details on my blog post here, Node API Authentication with JSON Web Tokens - the right way.



来源:https://stackoverflow.com/questions/35375530/how-do-i-add-a-json-web-token-to-each-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!