在Asp.Net核心Web应用程序中使用EasyAuth对Azure App Service上的AAD进行身份验证时,无法填充ClaimsPrincipal

Vai*_*hav 7 authentication azure-web-sites azure-active-directory asp.net-core

我们有一个基于Asp.Net核心的Web应用程序.它不包含任何配置的身份验证中间件.

我们托管Azure App Service并使用身份验证/授权选项(EasyAuth)对Azure AD进行身份验证.

身份验证效果很好 - 我们插入了必需的标头,我们可以在/.auth/me上看到经过身份验证的身份.但是HttpContext.User属性不会被填充.

这是Asp.Net核心的兼容性问题吗?或者我做错了什么?

Jon*_*ved 12

我创建了一个自定义中间件来填充User属性,直到Azure团队解决了这个问题.

它从应用程序服务身份验证中读取标头,并创建一个将被其识别[Authorize]并具有声明权限的用户name.

// Azure app service will send the x-ms-client-principal-id when authenticated
app.Use(async (context, next) =>
{

    // Create a user on current thread from provided header
    if (context.Request.Headers.ContainsKey("X-MS-CLIENT-PRINCIPAL-ID"))
    {
        // Read headers from Azure
        var azureAppServicePrincipalIdHeader = context.Request.Headers["X-MS-CLIENT-PRINCIPAL-ID"][0];
        var azureAppServicePrincipalNameHeader = context.Request.Headers["X-MS-CLIENT-PRINCIPAL-NAME"][0];

        // Create claims id
        var claims = new Claim[] {
        new System.Security.Claims.Claim("http://schemas.microsoft.com/identity/claims/objectidentifier", azureAppServicePrincipalIdHeader),
        new System.Security.Claims.Claim("name", azureAppServicePrincipalNameHeader)
        };

        // Set user in current context as claims principal
        var identity = new GenericIdentity(azureAppServicePrincipalIdHeader);
        identity.AddClaims(claims);

        // Set current thread user to identity
        context.User = new GenericPrincipal(identity, null);
    };

    await next.Invoke();
});
Run Code Online (Sandbox Code Playgroud)


Chr*_*lum 11

是的,这是一个兼容性问题.不幸的是,ASP.NET Core不支持从IIS模块(如Easy Auth)流向身份信息到应用程序代码.这意味着HttpContext.User和类似的代码将不像常规ASP.NET那样工作.

现在的解决方法是从服务器代码调用Web应用程序的/.auth/me端点以获取用户声明.然后,您可以使用x-ms-client-principal-id请求标头值作为缓存密钥,根据需要缓存此数据./.auth/me调用需要进行适当的身份验证,方法与调用Web应用程序需要进行身份验证的方式相同(auth cookie或请求标头令牌).


小智 5

我写了一个小的基本中间件来做到这一点.它将基于.auth/me端点创建一个标识.身份在身份验证管道中创建,以便[authorize]属性和策略与身份一起使用.

你可以在这里找到它:

https://github.com/lpunderscore/azureappservice-authentication-middleware

或者在nuget上:

https://www.nuget.org/packages/AzureAppserviceAuthenticationMiddleware/

添加后,只需将此行添加到您的启动中:

app.UseAzureAppServiceAuthentication();