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

feita há 2 anos412 visualizações
3 Respostas
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
respondido há 2 anos
1
Resposta aceita

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;
                            }
                        }
                    }
                }
            }
        }
respondido há um ano
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>
}
respondido há 2 anos
  • How are you doing the login to Cognito? Are you using the .NET SDK on the server side to perform the authentication?

Você não está conectado. Fazer login para postar uma resposta.

Uma boa resposta responde claramente à pergunta, dá feedback construtivo e incentiva o crescimento profissional de quem perguntou.

Diretrizes para responder a perguntas