gpt4 book ai didi

json - 如何向每个 header 添加 json 网络 token ?

转载 作者:太空狗 更新时间:2023-10-29 17:11:52 26 4
gpt4 key购买 nike

所以我正在尝试使用 JSON 网络 token 进行身份验证,并且正在努力弄清楚如何将它们附加到 header 并根据请求发送它们。

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

这是我的登录信息

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

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

一些 Node.js 登录代码

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

现在我只是试图通过 Angular 服务将它传递回具有此服务的节点。

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

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

我在任何地方都没有出错,但是当它到达我的节点服务器时,我从未在 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 请求中添加 token 。

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。在您的主模块声明中,将以下内容添加到提供程序数组中:

应用程序模块.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 提供程序。例如:

用户服务.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

关于json - 如何向每个 header 添加 json 网络 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35375530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com