我有一个在前端使用 ng2 (rc4) 运行的 ExpressJS API。我目前正在阅读如何使用 JWT 保护我的 API 上的某些端点。
目前,我可以从前端发送登录请求,将其拾取、检查,如果有效,则在响应中传回 JWT。然后我将其添加到本地存储。
然后,对于每个请求,我都会在标头中传递令牌。如果我在响应中收到 403,我计划将用户重定向到登录页面。
我目前的问题是,当我将请求传递给 API 时,我收到 403 响应。
我已经提取了我认为与以下相关的代码:
Express API - auth.js - 当一个 http 请求被发送到一个受保护的端点时被调用
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 发送的令牌将被接受且有效。
任何关于我哪里出错的建议将不胜感激。
编辑:好的,如果我更新以下内容:
headers.append('Authorization', `Bearer ${authToken}`);
现在是这样
headers.append('x-access-token', `${authToken}`);
它有效,但是我不确定这是否是最佳做法?