Logged in User Details In Azure AD App Service

Idenifying the Logged-In User in Azure AD

Lately I have been experimenting with Azure AD and putting Apps behind Azure AD. Once they are behind Azure AD Auth i wanted to make decisions based on the logged in user and it turned out to be a bit of a adventure trying to get those values.

I will document two different ways of obtaining authenticated user. one via python and one via javascript.

A bit of googling made me realize that behind Azure AD Auth application get bunch fo extra headers send to them as outlined here One of them being “X-Ms-Client-Principal-Name” request header. This contains the username of the loggedin user. There any multiple other headers which might come handy later.

A simply python flask app code to get the header is

@app.route("/testenv")
def testenv():

    username=request.headers.get("X-Ms-Client-Principal-Name")
    return render_template('index.html',name=username)

with accomplaying index.html being

<h1>Hello {{ name | safe}}</h1>

With this solved from backend I also wanted to explore how we can obtain the same values via client side. The request headers cant be seen in client side. This is where I had to dig into the azure ad documentation and that lead to .auth/me url endpoint. This endpoint requires token store to be active

Knowing myself and my javascript skills i took help of a friend Savan to make some basic javascript code. a bit of tweaking of code between the two of us got the final base PoC.

    function data() {
            var xhttp = new XMLHttpRequest();       
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    var myObj = JSON.parse(this.responseText);
                    username=myObj[0].user_id;
                    console.log(myObj[0].user_id);
                }
        };
        xhttp.open("GET", "https://"+document.domain+"/.auth/me", true);
        xhttp.withCredentials = true;
        xhttp.send();
    }
    data();

Note: This was originally published on a defunct subdomain https://til.anantshri.info/post/azure_ad_loggedin_user/ ported to blog.anantshri.info to retain the content.

Do you like what you read, What to share it

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.