【Azure Developer】在App Service上放置一个JS页面并引用msal.min.js成功获取AAD用户名示例

发布时间 2023-10-11 22:23:45作者: 路边两盏灯

问题描述

在App Service上放置一个JS页面并引用msal.min.js,目的是获取AAD用户名并展示。

问题解答

示例代码

<!DOCTYPE html>
<html>
<head>
    <title>Azure Service</title>
</head>
<script type="text/javascript" src="https://alcdn.msauth.net/lib/1.4.18/js/msal.min.js"></script>

<body>
    <h1>Welcome to Azure Service</h1>
    <p id="current-user"></p>
    
    <script>
        // 定义Azure AD应用程序的客户端ID和租户ID
        var clientId = 'xxxxxxxx-xxxx-xxxx-8906-xxxxxxxx';
        var tenantId = 'xxxxxxxx-xxxx-xxxx-8f9f-xxxxxxxx';

        // 创建Msal应用程序实例
        var msalConfig = {
            auth: {
                clientId: clientId,                    
                authority: 'https://login.partner.microsoftonline.cn/'+tenantId,
                redirectUri: window.location.origin
            }
        };
        var msalApplication = new Msal.UserAgentApplication(msalConfig);
        // 检查用户是否已经登录
        if (msalApplication.getAccount()) {
            // 获取当前用户信息
            var user = msalApplication.getAccount();

            // 更新HTML元素的内容
            document.getElementById('current-user').textContent = 'Current User: ' + user.name;
        } else {
            // 用户未登录,执行登录流程
            // 用户未登录,执行登录流程
            msalApplication.loginPopup()
                .then(function (response) {
                    // 登录成功,获取用户信息
                    var user = msalApplication.getAccount();

                    // 更新 HTML 元素的内容
                    document.getElementById('current-user').textContent = 'Current User: ' + user.name;
                })
                .catch(function (error) {
                    // 登录失败,处理错误
                    console.error('Error:', error);
                });
        }
    </script> 
</body>
</html>

 

注意事项

1) 在为 msalConfig 配置 authority 的时候,需要注意用指定AAD Application的TenantID,不要使用common代替,不然会遇见如下错误

ServerError: AADSTS50194: Application 'xxxxxxxx-3508-xxxx-8906-xxxx'(xxxxServicePrincipal) is not configured as a multi-tenant application. Usage of the /common endpoint is not supported for such applications created after '10/15/2018'. Use a tenant-specific endpoint or configure the application to be multi-tenant.

 

2) 一定要为AAD Application配置回调地址(Redirect URIs), 不然会得到 AADSTS500113: No reply address is registered for the application.

3)   AAD Application中配置的回调地址一定是正确的地址,避免登陆后回调错误

 

登录演示

 

 

 

参考资料

Microsoft Authentication Library for JavaScript (MSAL.js)  : https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/msal-lts/lib/msal-core

Use MSAL in a national cloud environment : https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-national-cloud?tabs=javascript