如何验证 Microsoft Graph API jwt access_token 并保护您的 API? [英] How to validate Microsoft Graph API jwt access_token and secure your API?

查看:53
本文介绍了如何验证 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.nonce(需要一些特殊处理,我找不到任何关于特殊处理的文档)

<强>2.类型:智威汤逊

有效载荷:

"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、Following (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""

我这几天一直被困在这里,任何帮助都是救命稻草.

关键点:

  1. 我尝试在 jwt.io 中验证 access_token (https://nicksnettravels.builttoroam.com/post/2017/01/24/Verifying-Azure-Active-Directory-JWT-Tokens.aspx)但我是没办法.

这里的 aud 是 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.

推荐答案

我尝试在 jwt.io 中验证 access_token (https://nicksnettravels.builttoroam.com/post/2017/01/24/Verifying-Azure-Active-Directory-JWT-Tokens.aspx) 但我无法.

据我所知,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.

这里的 aud 是 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?

我不知道 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.

代码中是否有问题,或者我需要调整我请求标头令牌的方式.

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

唯一让我印象深刻的是你做了很多不必要的配置.基本上配置应该是:

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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