首页 > 解决方案 > Azure Function 2.x 如何访问 stable_sid?

问题描述

当我使用 v1 编写我的 Azure 函数时,我能够sid像这样访问用户:

public static bool TryGetUserId(out string userId)
{
    userId = string.Empty;

    IPrincipal currentPrincipal = ClaimsPrincipal.Current;

    if (currentPrincipal is null)
        return false;

    userId = currentPrincipal.GetNameIdentifier();

    return false == string.IsNullOrWhiteSpace(userId);
}

然后我将我的 Azure Function 移至 v2 预览版,并且我读到ClaimsPrincipal 不再含水了。我结束了使用以下算法:

public static bool TryGetUserId(HttpRequestMessage request, out string userId)
{
    userId = string.Empty;

    KeyValuePair<string, IEnumerable<string>> principalId = request.Headers.FirstOrDefault(header => string.Equals(header.Key, "X-MS-CLIENT-PRINCIPAL-ID", StringComparison.InvariantCulture));

    if (principalId.Value.Count() != 1)
         return false;

    userId = principalId.Value.First();

    return false == string.IsNullOrWhiteSpace(userId);
}

这是我的 Azure 函数的示例:

[FunctionName("FindAccount")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequestMessage request, ILogger logger)
{
    try
    {
        if (false == FunctionHelper.TryGetUserId(request, out userId))
            return new HttpResponseMessage(HttpStatusCode.Unauthorized);

        // Looks for an account matching the sid.
    }
    catch (AccountNotFoundException)
    {
        logger.LogInformation($"No account has been found for user.");

        return new HttpResponseMessage(HttpStatusCode.NoContent);
    }
}

它不再起作用,因为标题不再是 sid,而是一个longint值,无论我使用的是 Google 帐户还是 Microsoft 帐户。

设置

我有一个 iOS 应用程序,它将用户定向到 Google 或 Microsoft 进行身份验证,然后 iOS 应用程序连接特定端点(/.auth/login/microsoftaccount/.auth/login/google)上的 Azure 函数以发布收到的令牌,如 Microsoft文档中所述。

问题

Azure Function v2 如何访问用户的sid

标签: c#azureazure-functions

解决方案


尝试以下方法并遵循文档。这已通过代码片段进行了详细讨论。

public static async Task<IActionResult>  Run(HttpRequest req, ILogger log, ClaimsPrincipal principal)
{
    log.LogInformation("C# HTTP trigger function processed a request."); 

    var isAuthenticated = principal.Identity.IsAuthenticated; 
    var idName = string.IsNullOrEmpty(principal.Identity.Name) ? "null" : principal.Identity.Name;
    log.LogInformation($"principal.Identity.IsAuthenticated = '{isAuthenticated}' and principal.Identity.Name = '{idName}'");
    var owner = (principal.FindFirst(ClaimTypes.NameIdentifier))?.Value;
    
    return new OkObjectResult($"principal.Identity.IsAuthenticated = '{isAuthenticated}' and principal.Identity.Name = '{idName}'");
    
}

private static string GetIdentityString(ClaimsIdentity identity)
{
    var userIdClaim = identity.FindFirst(ClaimTypes.NameIdentifier);
    if (userIdClaim != null)
    {
        // user identity
        var userNameClaim = identity.FindFirst(ClaimTypes.Name);
        return $"Identity: ({identity.AuthenticationType}, {userNameClaim?.Value}, {userIdClaim?.Value})";
    }
    else
    {
        // key based identity
        var authLevelClaim = identity.FindFirst("http://schemas.microsoft.com/2017/07/functions/claims/authlevel");
        var keyIdClaim = identity.FindFirst("http://schemas.microsoft.com/2017/07/functions/claims/keyid");
        return $"Identity: ({identity.AuthenticationType}, {authLevelClaim?.Value}, {keyIdClaim?.Value})";
    }
}


推荐阅读