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

질문됨 2년 전412회 조회
3개 답변
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
답변함 2년 전
1
수락된 답변

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;
                            }
                        }
                    }
                }
            }
        }
답변함 일 년 전
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>
}
답변함 2년 전
  • How are you doing the login to Cognito? Are you using the .NET SDK on the server side to perform the authentication?

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠