简体   繁体   中英

Jwt Authorization .NET Core 2.0 with angular always return Unauthorized (HTTP 401)

I am trying to autherize the Active Directory user by using using MsAdalAngular6Service that is Azure Active Directory Authentication Library which authenticate user at client side with using jwt bearer token.

My angular code looks a like

constructor(private adalSvc: MsAdalAngular6Service) {
    var token = this.adalSvc.acquireToken('graphApiUri').subscribe((token) => {
      localStorage.setItem('token', token);
    });
  }
  GetUser() {
     let httpOptions = {
      headers: new HttpHeaders({
       'Authorization': 'Bearer ' + localStorage.getItem('token'),

      })
    }
    var token = localStorage.getItem('token');
    return this._http.get(this.myAppUrl + 'api/Member/getuser', httpOptions)
      .map((res: Response) => res.json())
  } 
  }

here I am using the acquire token to authenticate the user and my startup.cs file code is as below.

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.Authority = "https://login.microsoftonline.com/6fa7661f-b743-4046-b913-06c1c48eb54e";
                 //options.Audience = "https://graph.microsoft.com";
                options.TokenValidationParameters.ValidateLifetime = true;
                options.TokenValidationParameters.ClockSkew = TimeSpan.Zero;
            });

and my controller action is as below.

    [Authorize]
    [HttpGet]
    [Route("getuser")]
    public async Task<User> GetUserInfoAsync()
    {
        var token = Request.Headers["Authorization"].ToString();
    }

but whenever I am calling this action through angular it alway returns the unautherized 401 error.

the acquire token always returns the UnAutherize 401 but when I am passing Access token it is not showing 401 but i need to pass acquire token only. not able to figure out where am going wrong.

Make sure you have AuthenticationSchemes in your controller like this

[Authorize(AuthenticationSchemes = "Bearer")]
[Route("api/[controller]/")]
public class AssetController : Controller

Also make sure you have the token in this line

var token = localStorage.getItem('token');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM