- Neueste
- Die meisten Stimmen
- Die meisten Kommentare
Generally speaking, when you log in with Cognito there's an identity token that's returned as part of the authentication response. This ID Token (in JWT format -- see this documentation for details on format) should be put into your session data -- most of the time this means storing the JWT in a browser cookie and passing it with subsequent requests to the web server. So if that's how you're storing your session data you should be able to pull the unique identifier of the logged in user from the sub
field in the ID Token stored in HttpContext.Request.Cookies
on the server side. You can also pull other useful fields like email
and cognito:username
.
Hi, I found the solution the my problem and i want to share it with you. I'm using the hosted UI of Cognito. So, when you want to secure a page you put the tag [Authorize]. Here is the function to get the current user informations. The user variable is from the PageModel
public async Task GetCurrentUser()
{
if (User != null)
{
if (User.Identity != null)
{
if (User.Identity.IsAuthenticated)
{
var UserClaim = User.Claims.FirstOrDefault();
if (UserClaim != null)
{
if (UserClaim.Subject != null)
{
var username = (UserClaim.Subject.Claims.Count() > 2) ? UserClaim.Subject.Claims.ElementAt(2).Value : "";
var email = (UserClaim.Subject.Claims.Count() > 8) ? UserClaim.Subject.Claims.ElementAt(8).Value : "";
var token = (UserClaim.Subject.Claims.Count() > 3) ? UserClaim.Subject.Claims.ElementAt(3).Value : "";
UserData userData = new()
{
Name = username,
Email = email,
Token = token
};
UserInfos = userData;
}
}
}
}
}
}
Thanks a lot! So, I tried to get the JWT, but it didn't succeed. I found a javascript example on the Amazon documentation and that's exactly what I want (https://docs.aws.amazon.com/cognito/latest/developerguide/authentication.html). But, i get the error "AmazonCognitoIdentity is not defined".
So, this is my cshtml page. Is there a nuget package we need to import to use the AmazonCognitoIdentity in javascript?
@page
@{
ViewData["Title"] = "Secure";
}
<h2>Login</h2>
<p>@Model.Message</p>
@section Scripts {
<script type="text/JavaScript">
$(document).ready(function () {
alert("Start!!!");
var pooldata =
{
UserPoolID: '',
ClientId: ''
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(pooldata);
var cognitoUser = userPool.getCurrentUser();
if (cognitoUser != null)
{
alert("Welcome, " + cognitoUser.username);
}
else
{
alert("Welcome, not connected");
}
alert("End!!!");
});
</script>
}
Relevanter Inhalt
- AWS OFFICIALAktualisiert vor 2 Jahren
- AWS OFFICIALAktualisiert vor 2 Jahren
How are you doing the login to Cognito? Are you using the .NET SDK on the server side to perform the authentication?