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

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

问题描述

我在弄清楚如何验证.NET Core Web API中由AWS Cognito提供给客户端的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的变量应该是什么,而且一旦我终于知道了,就不知道如何从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

最后,尽管经过了很多随机的Google搜索和反复试验,我还是找到了一个(看似不是很有效的解决方案)解决方案.但是,我花了太多时间来做.出于这一点,再加上严重缺乏有关该主题的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(参数等,请参见此处:

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库,则可以通过观察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:

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

// 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天全站免登陆