简体   繁体   中英

How to retrieve the Azure Active Directory logged in user information from Javascript?

I have a web app where the client side is developed in Javascript. I have already enabled Azure AD login for my app by configuring it at portal.azure.com. Then, every time when this app loads, users are required to log in, if they have not. I would like to have some Javascript in my client side so the app knows the user name. Here is the code I have.

<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.11/js/adal.min.js"></script>
<script type="text/javascript">
var authContext = new AuthenticationContext({
        clientId: 'xxxx-xxx-xxxx',
        postLogoutRedirectUri: window.location
    });

    var user = authContext.getCachedUser();
    if (user) {
        window.alert("Signed in as " + user.userName);  
    } else{
        window.alert("Failed to get the user information");
    }
</script>

However, the variable user is always null. Can anybody help?

That seems you are using "Authentication / Authorization" feature of azure app service and the identity provide is azure ad . If you want to access the tokens from a client (like JavaScript in a browser), or if you want to get a richer set of information about the logged in user, you can also send an authenticated GET request to the /.auth/me endpoint. Javascript code below to get user claims is for your reference:

   <script type="text/javascript">
        $(document).ready(function ()
        {
            $.get("https://xxxxxx.azurewebsites.net/.auth/me", function (data, status) {
                for (var key in data[0]["user_claims"]) {
                    var obj = data[0]["user_claims"][key];
                    alert(obj["typ"]);   //claim type in user_claims
                    alert(obj["val"])    //claim value in user_claims                 
                }
            });
        });
   </script>

Thanks, Yan. That pretty solves my problem, only with little revision to your code. My situation is that I need to retrieve the user name first before generating the later part of my app. So, I removed the outer wrapper $(document).ready(function(){} . Correct me if I am wrong. Probably this out wrapper is telling this chunk of code to run after the entire app is loaded. Then, the final code is like this:

<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$.get("https://xxxxx.azurewebsites.net/.auth/me", function (data) {
        labeler = data[0]['user_id'];
        window.alert("You logged in as " + data[0]['user_id']);
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM