Search code examples
c#.netazuremodel-view-controlleradal

ADAL bearer token does not return username but aad client id


We have an desktop app which uses adal to authenticate the user, using this code:

AuthenticationResult result = null;
var context = new  AuthenticationContext(aadTenantDomain);
result = await context.AcquireTokenAsync(resourceId, clientId, returnUrl, new PlatformParameters(PromptBehavior.Auto));

This works fine and the returned AuthenticationResult has all the right user information. Now we call a web app web api controller hosted on azure with the access token obtained from AuthenticationResult:

var Client = new HttpClient();
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);

Which also correctly authorizes the user. Now in the web controller we use User.Identity.Name to get the username which was authorized by the access token. For many month til yesterday this worked well, but today User.Identity.Name returns the client id of the desktop app instead of a username. Anyone knows what migh be wrong?

This is the api auth configuration:

 public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {                   
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,                     
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    RoleClaimType = System.Security.Claims.ClaimTypes.Role,                         
                }
            });
    }

And this is an example controller function:

[Authorize]
public class dialplanController : ApiController
{
    public async Task<IHttpActionResult> GetMe()
    {
        var Me = db.dialplan.FirstOrDefault(d => d.email == User.Identity.Name);
        return Ok(Me);
    }
}

Solution

  • Using ClaimsPrincipal.Current?.FindFirst(ClaimTypes.Upn)?.Value returns the correct UPN of the current user or null if no upn is given.