ClaimsPrincipal.Current.Identity.Name从客户端验证时为空,在浏览器中正常

时间:2016-12-28 12:14:46

标签: c# azure-functions

我有以下Azure功能,

#r "Newtonsoft.Json"

using Newtonsoft.Json.Linq;
using System.Net;
using System.Security.Claims;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    try
    {
        JObject pJOtClaims = new JObject();
        foreach(Claim curClaim in  ClaimsPrincipal.Current.Identities.First().Claims)
        {
            pJOtClaims.Add(curClaim.Type, new JValue(curClaim.Value));
        }
        return(req.CreateResponse(HttpStatusCode.OK, $"{pJOtClaims.ToString(Newtonsoft.Json.Formatting.None)}"));
    }
    catch(Exception ex)
    {
        return(req.CreateResponse(HttpStatusCode.OK, $"{ex.Message}"));
    }
}

我仅为此功能应用配置了Facebook身份验证。此功能适用于浏览器内和客户端身份验证。当我在浏览器中调用此方法时,我得到了一大堆声明,包括我注册的Facebook电子邮件地址。当我从客户端身份验证调用此方法时,我得到以下声明,

{
    "stable_sid":"...",
    "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier":"...",
    "http://schemas.microsoft.com/identity/claims/identityprovider":"...",
    "ver":"...",
    "iss":"...",
    "aud":"...",
    "exp":"...",
    "nbf":"..."
}

不幸的是,这些都不包括我需要的Facebook电子邮件地址。我启用了&#34;电子邮件&#34; Facebook身份验证配置的范围。任何想法如何得到这个?

尼克。

1 个答案:

答案 0 :(得分:1)

好的,所以我还没有找到我想要的确切解决方案,但这应该让我了解。从技术上讲,我只需要在注册过程中使用电子邮件地址,之后我就可以使用stable_sid作为我所获得的身份的一部分。所以我所做的是将x-zumo-auth标头传递给“.auth / me”方法,获取我需要的属性。我正在使用这种方法

    public static async Task<String> GetAuthProviderParam(String iAuthMeURL,
        String iXZumoAUth,
        String iParamKey)
    {
        using (HttpClient pHCtClient = new HttpClient())
        {
            pHCtClient.DefaultRequestHeaders.Add("x-zumo-auth", iXZumoAUth);
            String pStrResponse = await pHCtClient.GetStringAsync(iAuthMeURL);
            JObject pJOtResponse = JObject.Parse(pStrResponse.Trim(new Char[] { '[', ']' }));
            if(pJOtResponse[iParamKey] != null)
            {
                return (pJOtResponse[iParamKey].Value<String>());
            }
            else
            {
                throw new KeyNotFoundException(String.Format("A parameter with the key '{0}' was not found.", iParamKey));
            }
        }
    }

这可以在函数中调用,

    if(req.Headers.Contains("x-zumo-auth"))
    {
        String pStrXZumoAuth = req.Headers.GetValues("x-zumo-auth").First();
        String pStrParam = await FunctionsHelpers.GetAuthProviderParam("https://appname.azurewebsites.net/.auth/me",
            pStrXZumoAuth,
            "user_id");
        //pStrParam = user_id
    }