简体   繁体   English

在 Angular 中实现 JWT 访问令牌后,从 API 获取列表时出现 401 错误

[英]Getting 401 Error while fetching list from API after implementing JWT access token in Angular

In my service.ts file i coded like this在我的 service.ts 文件中,我这样编码

getUsers(): Observable<any> {
    let httpOptions = new HttpHeaders().set('Authorization', 'Bearer ' + 
    this.securityService.securityObject.bearerToken);
    return this.http.get(environment.baseApiUrl + "user", { headers: httpOptions });
}

In the bearerToken we have token value, but the headers showing in the httpOptions is like below image.在 BearerToken 中,我们有令牌值,但httpOptions中显示的标头如下图所示。 (took from the console) (从控制台获取)

在此处输入图像描述

in my controller class i have在我的 controller class 我有

    [HttpGet]
    [Authorize]
    public async Task<IActionResult> Get()
    {

In my HttpInterceptor i have written like在我的 HttpInterceptor 我写过

  var token = localStorage.getItem("bearerToken");

  if (token) {
  const newReq = request.clone(
    {
      headers: request.headers
        .set('Authorization',
          'Bearer ' + token)
    });

  return next.handle(newReq);
}
else {
  return next.handle(request);
}

my local storage have my token value, but我的本地存储有我的令牌值,但是

When i debug the code what i can see is its not entering inside the clone is this is the reason for headers not any entries like my image.当我调试代码时,我可以看到它没有进入克隆内部,这就是标题没有像我的图像这样的任何条目的原因。 Is clone ok to use there?克隆在那里可以使用吗?

im use on the same way, i don't think it s this the problem, but i think you don't need to set also when you call the get user我以同样的方式使用,我认为这不是问题,但我认为您在调用 get 用户时也不需要设置

import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';
import { AuthenticationService } from './authentication.service';

@Injectable()
export class AuthInterceptorService implements HttpInterceptor {

    constructor(private injector: Injector) { }

    token:string;

    intercept(req, next) {
        const authService = this.injector.get(AuthenticationService);

        this.token = authService.getToken();

        const authRequest = req.clone({
            headers: req.headers.set('Authorization', 'Bearer ' + this.token) 
        });

        return next.handle(authRequest);
    }
}

if you look on the tools network it s already set from Interceptor Only:如果您查看工具网络,它已经从 Interceptor Only 设置:

getUsers(): Observable<any> {
    return this.http.get(environment.baseApiUrl + "user")
}

These were the main culprits which caused my issue这些是导致我的问题的罪魁祸首

  1. Like corsaro mentioned interceptors will take care our http request no need to mention it separately像 corsaro 提到的拦截器会处理我们的 http 请求,无需单独提及

  2. In my startup.cs file i was using before like this在我之前使用的startup.cs文件中

    app.UseAuthorization(); app.UseAuthentication();

I swapped it's order to我把它的顺序换成了

   app.UseAuthentication();
   app.UseAuthorization();
  1. In my interceptor class i modified header section to this在我的拦截器 class 中,我将 header 部分修改为此

     headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization':'Bearer ' + token })
  2. Copied JwtSettings which declared in the appsettings.json file to appsettings.development.json file for local debug将 appsettings.json 文件中声明的 JwtSettings 复制到 appsettings.development.json 文件中进行本地调试

Now after making these changes its working fine now:)现在进行这些更改后,它现在可以正常工作了:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 邮递员获得有效令牌,但从API获得401 - Postman gets a valid token but getting 401 from API 在将Hammock与Tumblr API结合使用以检索喜欢项时,为什么会出现此401未经授权的错误? - Why am I getting this 401 unauthorized error while using Hammock with the Tumblr API to retrieve likes? 标头中具有正确访问令牌的API调用给了我未经授权的401 - API call with correct access token in header gives me a 401 unauthorized 从我的C#应用​​程序访问webDav文件夹时出现401未经授权的错误? - Getting 401 unauthorized error while accessing webDav folder from my C# application? 将jwt交换为访问令牌会返回invalid_grant错误 - Exchange a jwt for an access token returns invalid_grant error Web API从自定义身份验证提供程序验证JWT承载令牌 - Web API Validate JWT Bearer Token from Custom Auth Provider DocuSign JWT 无效的访问令牌 - DocuSign JWT Invalid Access Token 如何在.NET(JWT验证令牌)中引发401未经授权的异常? - How to throw a 401 Unauthorized Exception in .NET (JWT Validate Token)? 为什么我的 JWT 令牌/断言会收到来自 Einstein OAuth 服务的“无效令牌”响应? - Why is my JWT token/assertion getting an "Invalid Token" response from Einstein OAuth service? 如何在 Web API C# 中验证来自同一用户的令牌 JWT 令牌 - How to Validate Token JWT Token that it comes from the same User in Web API C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM