如何使用 .AddJwtBearer() 在 .NET Core Web API 中验证 AWS Cognito JWT [英] How to validate AWS Cognito JWT in .NET Core Web API using .AddJwtBearer()

查看:43
本文介绍了如何使用 .AddJwtBearer() 在 .NET Core Web API 中验证 AWS Cognito JWT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在弄清楚如何验证由 AWS Cognito 在我的 .NET Core Web API 中提供给客户端的 JWT 时遇到了一些麻烦.

I was having some trouble figuring out how to go about validating a JWT given to the client by AWS Cognito inside my .NET Core Web API.

我不仅无法弄清楚 Microsoft.IdentityModel.Tokens.TokenValidationParameters 的变量应该是什么,而且一旦我终于做到了,我不知道如何检索 JWT 密钥从 https://cognito-idp.{region}.amazonaws.com/{pool ID}/.well-known/jwks.json

Not only could I not figure out what the variables for Microsoft.IdentityModel.Tokens.TokenValidationParameters were supposed to be, but once I finally did, I didn't know how to retrieve the JWT key set from https://cognito-idp.{region}.amazonaws.com/{pool ID}/.well-known/jwks.json

最后,虽然进行了大量的随机谷歌搜索和反复试验,但我找到了一个(看似不是非常有效的解决方案)解决方案.然而,我花了太多时间做这件事.考虑到这一点,再加上 AWS 相关文档严重缺乏这一事实,我决定发布此问答,以帮助其他人将来更轻松地找到此解决方案.

Finally, though a lot of random Googling and trial and error, I found a (seemingly-not-very-efficient solution) solution. However, I spent way too much time doing it. Citing that, plus the fact that AWS documentation on the subject is severely lacking, I decided to post this Q&A to help others find this solution more easily in the future.

如果有更好的方法来做到这一点,有人告诉我,因为除了下面列出的答案之外,我还没有找到一种方法来做到这一点.

If there's a better way to do this, somebody please tell me because I have yet to find a way to do this besides my answer listed below.

推荐答案

答案主要在于正确定义 TokenValidationParameters.IssuerSigningKeyResolver(参数等,见此处:https://docs.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.tokens.issuersigningkeyresolver?view=azure-dotnet).

The answer lies primarily in correctly defining the TokenValidationParameters.IssuerSigningKeyResolver (parameters, etc. seen here: https://docs.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.tokens.issuersigningkeyresolver?view=azure-dotnet).

这就是告诉 .NET Core 验证发送的 JWT 所针对的内容.还必须告诉它在哪里可以找到键列表.不一定要对密钥集进行硬编码,因为它经常由 AWS 轮换.

This is what tells .NET Core what to verify the JWT sent against. One must also tell it where to find the list of keys. One cannot necessarily hard-code the key set, as it is often rotated by AWS.

一种方法是从 IssuerSigningKeyResolver 方法内的 URL 获取并序列化列表.整个 .AddJwtBearer() 可能看起来像这样:

One way to do it would be to fetch and serialize the list from the URL inside the IssuerSigningKeyResolver method. The whole .AddJwtBearer() might look something like this:

Startup.cs ConfigureServices() 方法:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
                        {
                            // get JsonWebKeySet from AWS
                            var json = new WebClient().DownloadString(parameters.ValidIssuer + "/.well-known/jwks.json");
                            // serialize the result
                            var keys = JsonConvert.DeserializeObject<JsonWebKeySet>(json).Keys;
                            // cast the result to be the type expected by IssuerSigningKeyResolver
                            return (IEnumerable<SecurityKey>)keys;
                        },

                        ValidIssuer = "https://cognito-idp.{region}.amazonaws.com/{pool ID}",
                        ValidateIssuerSigningKey = true,
                        ValidateIssuer = true,
                        ValidateLifetime = true,
                        ValidAudience = "{Cognito AppClientID}",
                        ValidateAudience = true
                    };
                });

如果使用AWS Amplify等JS库,通过观察的结果,可以在浏览器的控制台中看到ValidIssuerValidAudience等参数Auth.currentSession()

If you use a JS library such as AWS Amplify, you can see parameters such as the ValidIssuer and ValidAudience in your browser's console by observing the result of Auth.currentSession()

利用上面实现的 JWT 身份验证以及使用控制器上的 [Authorize] 标记从 JS 客户端到 .NET Core Web API 的 REST 获取请求可能如下所示:

A REST fetch request from a JS client to a .NET Core Web API utilizing the JWT Authentication achieved above as well as using the [Authorize] tag on your controller might look something like this:

JS 客户端使用@aws-amplify/auth 节点包:

// get the current logged in user's info
Auth.currentSession().then((user) => {
fetch('https://localhost:5001/api/values',
  {
    method: 'GET',
    headers: {
      // get the user's JWT token given to it by AWS cognito 
      'Authorization': `Bearer ${user.signInUserSession.accessToken.jwtToken}`,
      'Content-Type': 'application/json'
    }
  }
).then(response => response.json())
 .then(data => console.log(data))
 .catch(e => console.error(e))
})

这篇关于如何使用 .AddJwtBearer() 在 .NET Core Web API 中验证 AWS Cognito JWT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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