How to validate AWS Cognito JWT in .NET Core Web API using .AddJwtBearer()

后端 未结 2 815
执笔经年
执笔经年 2020-12-25 08:21

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.

Not only could I not figure o

相关标签:
2条回答
  • 2020-12-25 08:53

    The provided answer here is only required if you need more fine grained control over validation.

    Otherwise the following code is sufficient to validate jwt.

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "{yourAuthorizationServerAddress}";
        options.Audience = "{yourAudience}";
    });
    

    Okta have a good article on this. https://developer.okta.com/blog/2018/03/23/token-authentication-aspnetcore-complete-guide

    When the JwtBearer middleware handles a request for the first time, it tries to retrieve some metadata from the authorization server (also called an authority or issuer). This metadata, or discovery document in OpenID Connect terminology, contains the public keys and other details needed to validate tokens. (Curious what the metadata looks like? Here’s an example discovery document.)

    If the JwtBearer middleware finds this metadata document, it configures itself automatically. Pretty nifty!

    0 讨论(0)
  • 2020-12-25 09:04

    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).

    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.

    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() method:

    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
                        };
                    });
    

    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()

    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 Client using @aws-amplify/auth node package:

    // 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))
    })
    
    0 讨论(0)
提交回复
热议问题