Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get logged in user with Azure Web Apps Auth

Azure Web App has a great global Authentication options.
I'm currently using Azure AD as 'Authentication Provider' and as 'Log in with...' as well:

screenshot of azure authentication

This works great but I can't figure how the get the username (email) of the currently signed in user. Many features of my app have this requirement.
Any ideas?

like image 905
nirsky Avatar asked Apr 12 '16 14:04

nirsky


2 Answers

There are several ways to do this. If you're using Azure AD and node.js, the easiest way is to look at the X-MS-CLIENT-PRINCIPAL-NAME HTTP request header. That will contain the email of the user.

If you want to get user information from some JavaScript code on the client, you can alternatively make an AJAX request to the site's /.auth/me endpoint. As long as the login session cookie (currently named AppServiceAuthSession) is included in the AJAX call (which happens by default), you'll get a JSON blob that contains not only the email, but also all other claims associated with the user. This technique works on the server-side as well.

like image 123
Chris Gillum Avatar answered Sep 21 '22 08:09

Chris Gillum


rehash of Chris Gillum answer, w/ minor additions


Reference: https://docs.microsoft.com/en-us/azure/app-service/app-service-authentication-how-to#access-user-claims

Client Side/SPA:

Via Endpoint: /.auth/me

axios.get("/.auth/me")
.then(r => {console.log(r.data)})

Note: This endpoint is only available if token-store is enabled (otherwise will return 404).

Note: Login session cookie (currently named AppServiceAuthSession) must be included in the AJAX call (which happens by default)


Server side:

A. Via HTTP Request Headers:

  • X-MS-CLIENT-PRINCIPAL-NAME #Email of user
  • X-MS-CLIENT-PRINCIPAL-ID
  • Potentially others (prefixed with X-MS-CLIENT-*)

B. Via /.auth/me endpoint (see above)

like image 25
PotatoFarmer Avatar answered Sep 17 '22 08:09

PotatoFarmer