How to get current connected cognito user

1

Hi, I'm using ASP .NET Core Razor with AWS Cognito. Sign in is working great, but i tried a lot of things and don't know how to get the ID or username of the connected user in C#. Pages are using the attribute [Authorize]. Can you help me to get the connected user? Thanks

posta 2 anni fa412 visualizzazioni
3 Risposte
2

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.

profile pictureAWS
con risposta 2 anni fa
1
Risposta accettata

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;
                            }
                        }
                    }
                }
            }
        }
con risposta un anno fa
0

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>
}
con risposta 2 anni fa
  • How are you doing the login to Cognito? Are you using the .NET SDK on the server side to perform the authentication?

Accesso non effettuato. Accedi per postare una risposta.

Una buona risposta soddisfa chiaramente la domanda, fornisce un feedback costruttivo e incoraggia la crescita professionale del richiedente.

Linee guida per rispondere alle domande