如何在角度6中将JWT令牌作为授权标头发送 [英] How to send JWT token as authorization header in angular 6

查看:93
本文介绍了如何在角度6中将JWT令牌作为授权标头发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我在组件.ts文件中使用了此静态代码,但该代码无法正常工作.它返回未经授权的(401).但是,当我将令牌作为查询字符串传递时,它可以正常工作.请提供.ts文件组件的工作示例.

Currently I used this static code in component .ts file but this one is not work. It returns unauthorized(401). But when I pass token as query string it works fine. Please give a working example for component .ts file.

    import { HttpClient, HttpResponse ,HttpHeaders} from '@angular/common/http';


    var t=`eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMFwvYXBpXC9sb2dpbiIsImlhdCI6MTUzNzcxNTMyNSwiZXhwIjoxNTM3NzE4OTI1LCJuYmYiOjE1Mzc3MTUzMjUsImp0aSI6IlBKWVhnSkVyblQ0WjdLTDAiLCJzdWIiOjYsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.1vz5lwPlg6orzkBJijsbBNZrnFnUedsGJUs7BUs0tmM`;

    var headers_object = new HttpHeaders();
        headers_object.append('Content-Type', 'application/json');
        headers_object.append("Authorization", "Bearer " + t);

        const httpOptions = {
          headers: headers_object
        };


   this.http.post(
                  'http://localhost:8000/api/role/Post', {limit:10}, httpOptions
                 ).subscribe(resp => {
                  this.roles = console.log(resp)
                  }
                );

推荐答案

您的代码的问题是HttpHeaders类是不可变的,因此,当您调用append时,它实际上会返回具有指定值的新实例,但不会修改原始对象.

The problem with your code is that the HttpHeaders class is immutable, so when you call append it actually returns a new instance with the specified value, but does not modify the original object.

尝试一下

var headers_object = new HttpHeaders().set("Authorization", "Bearer " + t);

默认情况下,HttpClient

如果您需要在所有API调用中发送一个Authorization令牌,那么最好按照Martin的建议使用拦截器

If you need to do send a the Authorization token in all your API calls, then it's better to use an interceptor as suggested by Martin

这篇关于如何在角度6中将JWT令牌作为授权标头发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆