How to validate AWS Cognito JWT in .NET Core Web API using .AddJwtBearer()
up vote
0
down vote
favorite
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 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
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.
.net-core jwt amazon-cognito asp.net-core-webapi jwk
add a comment |
up vote
0
down vote
favorite
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 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
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.
.net-core jwt amazon-cognito asp.net-core-webapi jwk
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
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 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
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.
.net-core jwt amazon-cognito asp.net-core-webapi jwk
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 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
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.
.net-core jwt amazon-cognito asp.net-core-webapi jwk
.net-core jwt amazon-cognito asp.net-core-webapi jwk
asked Nov 10 at 23:30
Nickdb93
197115
197115
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
up vote
0
down vote
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.getIdToken().getJwtToken()}`,
'Content-Type': 'application/json'
}
}
).then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e))
})
add a comment |
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
0
down vote
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.getIdToken().getJwtToken()}`,
'Content-Type': 'application/json'
}
}
).then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e))
})
add a comment |
up vote
0
down vote
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.getIdToken().getJwtToken()}`,
'Content-Type': 'application/json'
}
}
).then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e))
})
add a comment |
up vote
0
down vote
up vote
0
down vote
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.getIdToken().getJwtToken()}`,
'Content-Type': 'application/json'
}
}
).then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e))
})
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.getIdToken().getJwtToken()}`,
'Content-Type': 'application/json'
}
}
).then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e))
})
answered Nov 10 at 23:30
Nickdb93
197115
197115
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244446%2fhow-to-validate-aws-cognito-jwt-in-net-core-web-api-using-addjwtbearer%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown