首页 文章

ExpressJS / Angular 2 JWT令牌

提问于
浏览
0

我的前端有一个运行ng2(rc4)的ExpressJS API . 我目前正在阅读如何使用JWT保护API上的某些 endpoints .

目前,我可以从前端发送登录请求,检查并检查,如果有效,则在响应中传回JWT . 然后我将其添加到本地存储 .

对于每个请求,我然后在 Headers 中传递令牌 . 如果我在响应中收到403,我计划将用户重定向到登录页面 .

我目前的问题在于,当我将请求传递给API时,我收到了403响应 .

我已经拿出了我认为相关的代码如下:

Express API - auth.js - 当http请求发送到受保护的 endpoints 时调用此方法

function CheckTokenIsValid(req, res, next) {

    var token = req.body.token || req.query.token || req.headers['x-access-token'];

    if (token) {
        jwt.verify(token, app.get('superSecret'), function(err, decoded) {
            if (err) {
                return res.json({
                    success: false,
                    message: 'Failed to authenticate token.'
                });
            } else {
                req.decoded = decoded;
                next();
            }
        });
    } else {
        return res.status(403).send({
            success: false,
            message: 'No token provided.'
        });
    }
}

ng2 - home.component.ts - onTestGet()由home上的ngSubmit触发

export class HomeComponent {
getData: string;

constructor(private _contentService: ContentService) { }

onTestGet() {
    this._contentService.getContent('http://localhost:8080/api/config', '')
        .subscribe(
        data => this.getData = data.site,
        error => console.log('error'),
        () => console.log(this.getData)
        );
}

}

ng2 - content.service.ts - 这是由onTestGet()调用的

import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Http, URLSearchParams} from '@angular/http';
import {Headers} from '@angular/http';

@Injectable()
export class ContentService {
    constructor(private _http: Http) { }

    getContent(api: string, max: string) {
        return this.makeRequest(api, max);
    }

    private makeRequest(path: string, max: string) {

        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        let authToken = localStorage.getItem('auth_token');
        headers.append('Authorization', `Bearer ${authToken}`);

        let params = new URLSearchParams();
        params.set('results', max);
        let url = path;
        return this._http.get(url, { headers }).map(res => res.json());
    }
}

我可以从开发人员工具中看到,在正确存储登录令牌后,如果我通过POSTMAN发送的令牌被接受并且有效 .

Contents of local storage after log in

任何关于我出错的建议都将不胜感激 .

编辑:好的,如果我更新以下内容:

headers.append('Authorization', `Bearer ${authToken}`);

现在就是这样

headers.append('x-access-token', `${authToken}`);

它有效,但我不确定这是否是最佳做法?

1 回答

  • 1

    由于您在授权标头中发送令牌,因此可以通过替换以下内容在后端获取令牌:

    var token = req.body.token || req.query.token || req.headers['x-access-token'];
    

    通过

    const authorization = req.headers.authorization;
    
    let token;
    
    if (authorization) {
      token = authorization.split(' ')[1]; // since Bearer in 0 and your token is 1
    } else {
      return res.status(404).json({ error: 'No token provided' });
    }
    

相关问题