使用 Azure Web Apps Auth 获取登录用户

Get logged in user with Azure Web Apps Auth

Azure Web App 有一个很棒的全局身份验证选项。
我目前正在使用 Azure AD 作为 'Authentication Provider' 和 'Log in with...':

这很好用,但我不知道如何获取当前登录用户的用户名(电子邮件)。我的应用程序的许多功能都有此要求。
有什么想法吗?

有几种方法可以做到这一点。如果您使用的是 Azure AD 和 node.js,最简单的方法是查看 X-MS-CLIENT-PRINCIPAL-NAME HTTP 请求 header。这将包含用户的电子邮件。

如果您想从客户端的某些 JavaScript 代码中获取用户信息,您也可以向站点的 /.auth/me 端点发出 AJAX 请求。只要登录 session cookie(当前名为 A​​ppServiceAuthSession)包含在 AJAX 调用中(默认情况下发生),您将获得 JSON blob 不仅包含电子邮件,还包含与用户关联的所有其他声明。此技术也适用于 server-side。

如果您将 Passport-azuread 库与您的 nodejs 一起使用,您可以执行类似于以下代码片段的操作:

<% if (user) { %>
    <p>displayName: <%= user.displayName %></p>
    <p>givenName: <%= user.name.givenName %></p>
    <p>familyName: <%= user.name.familyName %></p>
    <p>Full User Data</p>
    <%- JSON.stringify(user) %>
<% } %>

您可以在此处找到 Node 的完整 Azure AD 示例: https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-openidconnect-nodejs/#5-create-the-views-and-routes-in-express-to-display-our-user-in-the-website

感谢@Chris 的回答,我能够编写一个函数,returns 登录用户的电子邮件。

    public static String getEmail(HttpContext context)
    {
        String identifier = "X-MS-CLIENT-PRINCIPAL-NAME";
        IEnumerable<string> headerValues = context.Request.Headers.GetValues(identifier);
        if (headerValues == null)
        {
            System.Diagnostics.Debug("No email found!");
            return "";
        }
        else { 
            System.Diagnostics.Debug(headerValues.FirstOrDefault());
            return headerValues.FirstOrDefault();
        }
    }

Chris Gillum answer 的改版,添加了少量内容


参考:https://docs.microsoft.com/en-us/azure/app-service/app-service-authentication-how-to#access-user-claims

客户Side/SPA:

通过端点:/.auth/me

axios.get("/.auth/me")
.then(r => {console.log(r.data)})

注意:此端点仅在启用token-store时可用(否则将return 404)。

注意: 登录 session cookie(当前名为 AppServiceAuthSession)必须包含在 AJAX 调用中(默认情况下发生)


服务器端:

一个。通过 HTTP 请求 Headers:

  • X-MS-CLIENT-PRINCIPAL-NAME #用户邮箱
  • X-MS-CLIENT-PRINCIPAL-ID
  • 可能还有其他人(前缀为 X-MS-CLIENT-*

乙。通过 /.auth/me 端点(见上文)