I have an app service hosted on azure. This is the code that runs on first page that loads.
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
var identity = HttpContext.Current.User.Identity.Name;
lblUserInfo.Text = $"Found User -- > {identity}";
return;
}
else
{
lblUserInfo.Text = "Name Unknown!";
}
}
When I run it locally, it correctly says "Name Unknown" in that label. On Azure the Authentication blade on the app service indicates that the service cannot be accessed without a login. In other words, the app can be accessed by people in the organization.
My understanding from the MSDN documentation is that HttpContext.Current.User can be used to fetch the user's name in the code. This is not working as the identity variable in the code is blank when I host on azure. The website label displays "Found User --> "
when it runs on Azure.
What else do I need to do in order to get the user's name in the code?
CodePudding user response:
How to get logged in user's name from App Service Hosted on Azure?
To get the current user in Azure Web App ,use
var UserName = ((System.Security.Claims.ClaimsIdentity)User.Identity).Claims.Where(c => c.Type == "name").FirstOrDefault().Value;
If you want to receive user logged in data from Azure Web App, you can try using Basic authentication with Azure Web App. Refer Authentication and authorization in Azure App Service.
We need to use OpenID Connect to authenticate users from an Azure AD tenant. Refer Integrate Azure AD into a web application using OpenID Connect
OR
App Service uses specific headers to communicate user claims to your application. These headers cannot be set by external requests, hence they are only present if they are set by App Service.
User's claims are available by injecting them into the request headers. External requests aren't allowed to set these headers, they are present only if set by App Service.
Use
X-MS-CLIENT-PRINCIPAL-NAME
as http resquest header to get the username. Refer ## Access user claims in app code
var UserName=httpRequest.Headers["X-MS-CLIENT-PRINCIPAL-NAME"].ToString();
- This works only in Azure Web App
- The ClaimsPrincipal instance can be used to retrieve authenticated user information.