How to Authenticate ASP.NET Core Web APIs using Azure App Service Authentication (Easy Auth)?

Asked 3 hours ago Updated 3 hours ago 16 views

0

Azure App Service Authentication (Easy Auth) offloads identity handling from your web application to the Azure hosting runtime. When enabled, App Service passes authenticated user claims to ASP.NET Core via HTTP request headers.

Extracting Easy Auth Headers

Azure App Service injects several headers into incoming requests after authenticating the user:

  • X-MS-CLIENT-PRINCIPAL-NAME: User's username or email address.
  • X-MS-CLIENT-PRINCIPAL-ID: Unique subject ID of the authenticated user.
  • X-MS-CLIENT-PRINCIPAL: Base64 encoded JSON string representing user claims.

Creating a Custom Authentication Handler

In corporate environments using Easy Auth, create a custom AuthenticationHandler to bind incoming identity headers to the ASP.NET Core ClaimsPrincipal:

using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;

public class EasyAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public EasyAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
                           ILoggerFactory logger,
                           UrlEncoder encoder) : base(options, logger, encoder) { }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Request.Headers.TryGetValue("X-MS-CLIENT-PRINCIPAL-NAME", out var userName))
        {
            return Task.FromResult(AuthenticateResult.NoResult());
        }

        var claims = new[] { new Claim(ClaimTypes.Name, userName!) };
        var identity = new ClaimsIdentity(claims, Scheme.Name);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, Scheme.Name);

        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}

0 Answers


Write Your Answer