Azure Apps EasyAuth声称使用.NET Core

时间:2017-02-15 21:48:26

标签: azure asp.net-core azure-web-sites

我想编写一些ASP .NET Core中间件来将Azure Apps EasyAuth HTTP标头转换为声明。我找到了两种方法:

  1. 解析EasyAuth在HTTP标头中提供的令牌。这似乎不是一个通用的解决方案,因为我必须编写代码来解析每个身份提供者的令牌。

  2. 向/.auth/me提出服务器端请求。这会返回一些我想要转换为声明的JSON,但我不确定是否必须手动执行此操作或者是否有框架支持。

  3. #2是最好的方法,是否有任何框架支持?

2 个答案:

答案 0 :(得分:5)

根据您的描述,我发现了类似的issue。众所周知,目前没有任何框架可供您实现。根据我的理解,如果您希望在使用Azure App Service EasyAuth时检索所有声明,我认为您最好向内置端点/.auth/me发出服务器端请求以检索声明为如下:

Startup.cs>配置

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];

        #region extract claims via call /.auth/me
        //invoke /.auth/me
        var cookieContainer = new CookieContainer();
        HttpClientHandler handler = new HttpClientHandler()
        {
            CookieContainer = cookieContainer
        };
        string uriString = $"{context.Request.Scheme}://{context.Request.Host}";
        foreach (var c in context.Request.Cookies)
        {
            cookieContainer.Add(new Uri(uriString), new Cookie(c.Key, c.Value));
        }
        string jsonResult = string.Empty;
        using (HttpClient client = new HttpClient(handler))
        {
            var res = await client.GetAsync($"{uriString}/.auth/me");
            jsonResult = await res.Content.ReadAsStringAsync();
        }

        //parse json
        var obj = JArray.Parse(jsonResult);
        string user_id = obj[0]["user_id"].Value<string>(); //user_id

        // Create claims id
        List<Claim> claims = new List<Claim>();
        foreach (var claim in obj[0]["user_claims"])
        {
            claims.Add(new Claim(claim["typ"].ToString(), claim["val"].ToString()));
        }

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

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

    await next.Invoke();
});

答案 1 :(得分:3)

我创建了一个中间件,您可以使用ez auth在.net核心中获取正确的身份。您可以在此处看到我的答案,其中包含nuget和source的链接:

Trouble getting ClaimsPrincipal populated when using EasyAuth to authenticate against AAD on Azure App Service in a Asp.Net Core web app