本文介绍了如何验证Microsoft Graph API jwt access_token并保护您的API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

场景:

我有一个angular5客户端应用程序,它使用hello.js来使用其Office 365凭据对用户进行身份验证.

I have an angular5 client application, which uses hello.js to authenticate users using their office 365 credentials.

客户代码:

  hello.init({
      msft: {
        id: configuration.AppID,
        oauth: {
          version: 2,
          auth: 'https://login.microsoftonline.com/' + configuration.TenantID + '/oauth2/v2.0/authorize'
        },
        scope_delim: ' ',
        form: false
      },
    },
      { redirect_uri: configuration.redirecturl }
    );
  }


  login() {

    hello('msft').login({ scope: 'User.Read People.Read', display: 'popup' })
      .then((authData: any) => {  // console.log(authData);

        this.zone.run(() => {

          // get profile
}

成功的响应是(出于安全原因进行了操纵)

A successful response is (Manipulated for security reasons)

{
   "msft":{
      "access_token":"REMOVED TOKEN HERE",
      "token_type":"Bearer",
      "expires_in":3599,
      "scope":"basic,User.Read,People.Read",
      "state":"",
      "session_state":"3b82898a-2b3f-445363f-89ae-d9696gg64ad3",
      "client_id":"672330148-2bb43-3080-9eee-1f46311f789c",
      "network":"msft",
      "display":"popup",
      "redirect_uri":"http://localhost:5653/",
      "expires":15245366.218
   }
}

已解码的access_token具有以下几个键:

The decoded access_token has these few keys:

标题:

1.随机数(需要一些特殊处理,我找不到有关特殊处理的任何文档)

2.典型:JWT

有效载荷:

"aud":" https://graph.microsoft.com ",

"aud": "https://graph.microsoft.com",

一旦收到access_token,我将在每次调用的授权标头中将access_token发送到我的后端API.目标是验证令牌,并且仅在access_token得到验证和授权的情况下才发送成功响应.如果失败,则响应为401 Unauthorized.

Once the access_token is received, I am sending the access_token in authorization header of every call to my backend API. The goal is to validate the token and only send a successful response if the access_token is validated and authorized. If unsuccessful, 401 Unauthorized is the response.

用于验证access_token的API代码,ASP .NET CORE 2,其后( https://auth0.com/blog/securing-asp-dot-net-core-2-applications-with-jwts/)

API Code to validate access_token, ASP .NET CORE 2, Following (https://auth0.com/blog/securing-asp-dot-net-core-2-applications-with-jwts/)

namespace JWT
{
  public class Startup
  {
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
          options.TokenValidationParameters = new TokenValidationParameters
          {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
          };
        });

      services.AddMvc();
    }
  }
}

// other methods
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseAuthentication();

    app.UseMvc();
}

在appsettings.json中,我有:

In appsettings.json I have:

{   "Jwt": {
    "Key": "verySecretKey", **(I got the key from https://login.microsoftonline.com/common/discovery/keys with the kid value in access_token header)**
    "Issuer": "https://sts.windows.net/49bcf059-afa8-4bf9-8470-fad0c9cce27d/",   } }

最后,我收到的错误是:"WWW-Authenticate→Bearer error ="invalid_token",error_description =未找到签名密钥""

Finally, the error I receive is :"WWW-Authenticate →Bearer error="invalid_token", error_description="The signature key was not found""

过去几天以来我一直被困在这里,任何帮助都是救生员.

I have been stuck here since past few days, any help will be life savior.

要点:

  1. 我试图验证jwt.io中的access_token( https://nicksnettravels.builttoroam.com/post/2017/01/24/Verifying-Azure-Active-Directory-JWT-Tokens.aspx ),但我当时不能.

此处的音频为 https://graph.microsoft.com ,我不确定是否需要以及为什么需要将aud更改为我的客户ID.我该怎么办?

The aud here is https://graph.microsoft.com, I am not sure if I need to and why do I need to change aud to my client id. how do I do that?

代码中是否有错误,还是需要调整请求标头令牌的方式?

Is there something wrong in the code or do i need to tweak the way I am requesting header tokens.

如果您需要更多信息,请告诉我.

Please let me know if you need more information.

推荐答案

据我所见,Microsoft Graph API访问令牌的签名与其他访问令牌的签名不同.您无需验证用于其他API的令牌,这是它们的工作.

Microsoft Graph API access tokens are signed differently from other access tokens from what I can see.You do not need to validate tokens that are meant for another API, it is their job.

我不知道HelloJS,但是在使用response_type=id_token token进行身份验证后,您应该能够获得ID令牌.然后,您需要将其附加到请求.它应该以您的客户ID作为受众.

I don't know about HelloJS, but you should be able to get an Id token after authentication with response_type=id_token token.Then you need to attach that to the requests.It should have your client id as the audience.

对我而言,唯一一件值得一提的事就是您正在做很多不必要的配置.基本上,配置应为:

The only thing that stands out to me is that you are doing a lot of unnecessary configuration.Basically the configuration should be:

.AddJwtBearer(o =>
{
    o.Audience = "your-client-id";
    o.Authority = "https://login.microsoftonline.com/your-tenant-id/v2.0";
})

处理程序将在启动时自动获取公共签名密钥.在应用程序中对签名密钥进行硬编码并不是一个好主意,因为当AAD完成签名密钥翻转时,应用程序将中断.

The handler will automatically fetch the public signing keys on startup.It's not really a good idea to hard-code signing keys in your app since your app will break when AAD finishes signing key rollover.

这篇关于如何验证Microsoft Graph API jwt access_token并保护您的API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 17:12