typescript Angular 5 在使用 httpClient 发布之前将令牌添加到标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50132753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 5 Add Token to header before posting with httpClient
提问by davidxxx
I am using a restapi and it requires that I add a token to the header before I can create a new record.
我正在使用 restapi,它要求我在创建新记录之前向标头添加一个令牌。
Right now I have a service to create a new record which looks like this:
现在我有一个服务来创建一个新的记录,它看起来像这样:
service.ts
服务.ts
create(title, text) {
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
headers = headers.append('Authorization', token); // Not added yet as this is the reason for the question
return this.http.post('http://myapi/api.php/posts', {
title: 'added title',
text: 'added text'
}, { headers });
}
app.component.ts
app.component.ts
add() {
this.service.create('my title', 'body text').subscribe(result => {
console.log(result);
});
}
The problem with this is that it won't let me add the new record because it requires a token and in order to get a token I need to run this:
这样做的问题是它不会让我添加新记录,因为它需要一个令牌,为了获得一个令牌,我需要运行这个:
getToken() {
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
return this.http.post('http://myapi/api.php/user', {
username: 'admin',
password: 'password'
}, { headers });
}
My question is...How do I get this two together into one call instead of two...or when is the best way to do this?
我的问题是......我如何将这两个放在一个调用中而不是两个调用中......或者何时是最好的方法?
回答by Razvan Dumitru
Apart from what @Pardeep Jain already mentioned, you can add an interceptor (> Angular version 4, you mentioned you're using 5) for your HttpClient that will automatically add Authorization headers for all requests.
除了@Pardeep Jain 已经提到的内容之外,您还可以为您的 HttpClient 添加一个拦截器(> Angular 版本 4,您提到您使用的是 5),它将自动为所有请求添加授权标头。
If you need top be authenticated for only one request, it's better to keep things simple and use Pardeep's solution.
如果您只需要对一个请求进行身份验证,最好保持简单并使用 Pardeep 的解决方案。
If you want to be authenticated for most of your requests, then add an interceptor.
如果您希望对大多数请求进行身份验证,请添加拦截器。
module, let's say app.module.ts
模块,让我们说 app.module.ts
@NgModule({
//...
providers: [
//...
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
},
//...
]
//...
})
and your jwt interceptor, let's say jwt.interceptor.ts
和你的 jwt 拦截器,让我们说 jwt.interceptor.ts
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private injector: Injector, private router: Router) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
headers: req.headers.set('Authorization', /* here you fetch your jwt */this.getToken())
.append('Access-Control-Allow-Origin', '*')
});
return next.handle(authReq).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (response: HttpErrorResponse) => { });
}
getToken() {
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
return this.http.post('http://myapi/api.php/user', {
username: 'admin',
password: 'password'
}, { headers });
}
}
If you want to read something, more here: https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8
如果您想阅读更多内容,请点击此处:https: //medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8
回答by davidxxx
My question is...How do I get this two together into one call instead of two...or when is the best way to do this?
我的问题是......我如何将这两个放在一个调用中而不是两个调用中......或者何时是最好的方法?
You should not.
Authentication is one thing that should be performed a single time for the client or as the authentication ticket has expired.
Posting some content is another thing that you should not mix with authentication.
你不应该。
身份验证是应该为客户端执行一次或在身份验证票已过期时执行的一件事。
发布某些内容是另一件不应与身份验证混用的事情。
So authenticate the client once and store the ticket.
Then pass the ticket in the header for any request to a secured endpoints/methods. Or use a transverse way as an interceptor to set it in the send requests if you don't want to repeat the code.
因此,对客户端进行一次身份验证并存储票证。
然后将任何请求的标头中的票证传递给安全的端点/方法。或者如果不想重复代码,可以使用横向方式作为拦截器在发送请求中进行设置。
回答by Pardeep Jain
The code should be like this -
代码应该是这样的——
create(title, text) {
let headers: HttpHeaders = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
headers.append('Authorization', token);
return this.http.post('http://myapi/api.php/posts', {
title: 'added title',
text: 'added text'
}, { headers });
}