You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS(1.4.x)与ASP.NET Web API集成Azure AD单点登录(替换已废弃ADAL采用MSAL)的改造示例咨询

没问题!我刚好做过类似的适配——毕竟ADAL确实已经被微软弃用了,咱们改用MSAL.js v1.x(因为AngularJS 1.4.x不支持最新的MSAL版本)来实现Azure AD身份验证和单点登录,下面是前端(AngularJS)和后端(ASP.NET Web API)的具体修改步骤及代码示例:

AngularJS 1.4.x 前端修改

1. 引入MSAL.js库

可以直接使用CDN引入兼容AngularJS 1.4的MSAL版本:

<script src="https://alcdn.msauth.net/lib/1.4.16/js/msal.min.js"></script>

2. 配置MSAL并封装身份验证服务

在你的AngularJS应用中,创建一个全局的MSAL配置和身份验证服务,处理登录、登出、令牌获取逻辑:

angular.module('yourAppName', [])
  // 配置Azure AD参数
  .constant('msalSettings', {
    clientId: '你的Azure AD客户端ID', // 从Azure门户获取的SPA应用ID
    tenantId: '你的租户ID', // 可以是租户GUID或域名(如xxx.onmicrosoft.com)
    redirectUri: window.location.origin + '/', // 登录后跳转回应用的地址
    apiScope: 'api://你的Web API应用ID/access_as_user' // Web API的权限范围
  })
  // 封装身份验证服务
  .service('azureAuthService', ['msalSettings', function(msalSettings) {
    // 初始化MSAL实例
    const msalInstance = new Msal.UserAgentApplication(
      msalSettings.clientId,
      `https://login.microsoftonline.com/${msalSettings.tenantId}`,
      (errorDesc, token, error, tokenType) => {
        // 登录回调处理
        if (token) {
          console.log('登录成功,获取到令牌');
        } else {
          console.error('登录失败:', errorDesc);
        }
      },
      { cacheLocation: 'localStorage' } // 用localStorage存储令牌缓存
    );

    // 弹出登录窗口
    this.login = () => {
      return msalInstance.loginPopup({
        scopes: ['openid', 'profile', msalSettings.apiScope]
      }).then(() => msalInstance.getAccount());
    };

    // 登出
    this.logout = () => msalInstance.logout();

    // 获取访问Web API的令牌(静默优先,失败则弹窗)
    this.getApiToken = () => {
      return msalInstance.acquireTokenSilent({ scopes: [msalSettings.apiScope] })
        .then(res => res.accessToken)
        .catch(err => msalInstance.acquireTokenPopup({ scopes: [msalSettings.apiScope] })
          .then(res => res.accessToken));
    };

    // 判断是否已登录
    this.isAuthenticated = () => msalInstance.getAccount() !== null;
  }])
  // HTTP拦截器:给所有API请求添加Authorization头
  .factory('authInterceptor', ['azureAuthService', '$q', function(azureAuthService, $q) {
    return {
      request: function(config) {
        // 只给你的Web API地址添加令牌
        if (azureAuthService.isAuthenticated() && config.url.startsWith('/api/')) {
          return azureAuthService.getApiToken().then(token => {
            config.headers.Authorization = `Bearer ${token}`;
            return config;
          }).catch(err => $q.reject(err));
        }
        return config;
      }
    };
  }])
  // 注册拦截器
  .config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('authInterceptor');
  }]);

3. 登录/登出控制器示例

在页面控制器中调用身份验证服务:

angular.module('yourAppName')
  .controller('AuthController', ['azureAuthService', function(azureAuthService) {
    const vm = this;

    vm.login = () => {
      azureAuthService.login().then(user => {
        console.log('当前登录用户:', user.name);
        // 登录成功后跳转到主页或业务页面
      }).catch(err => alert('登录失败:' + err.message));
    };

    vm.logout = () => azureAuthService.logout();
    vm.isLoggedIn = () => azureAuthService.isAuthenticated();
  }]);

ASP.NET Web API 后端修改

1. 安装必要的NuGet包

在Web API项目中安装以下包:

Install-Package Microsoft.Owin.Security.ActiveDirectory
Install-Package Microsoft.Owin.Host.SystemWeb

2. 配置OWIN中间件验证Azure AD令牌

创建Startup.cs文件(如果没有的话),添加Azure AD Bearer令牌验证:

using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
using System.Configuration;
using System.IdentityModel.Tokens;

[assembly: OwinStartup(typeof(YourWebApiNamespace.Startup))]
namespace YourWebApiNamespace
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Tenant = ConfigurationManager.AppSettings["AzureADTenant"],
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidAudience = ConfigurationManager.AppSettings["AzureADAudience"]
                        // 可选:如果需要验证令牌过期、签名等,默认已经开启
                    }
                });
        }
    }
}

3. 在Web.config中添加Azure AD配置

<appSettings>
  <!-- Azure AD租户信息 -->
  <add key="AzureADTenant" value="你的租户ID或域名" />
  <!-- Web API的应用ID URI,从Azure门户获取 -->
  <add key="AzureADAudience" value="api://你的Web API应用ID" />
</appSettings>

4. 保护API控制器

在需要身份验证的控制器上添加[Authorize]属性:

using System.Web.Http;

namespace YourWebApiNamespace.Controllers
{
    [Authorize]
    public class BusinessController : ApiController
    {
        // GET api/business/data
        public IHttpActionResult Get()
        {
            // 获取当前用户信息(可选)
            var user = User.Identity.Name;
            return Ok(new { message = $"已通过Azure AD验证,当前用户:{user}" });
        }
    }
}

关键配置注意事项

  • Azure AD门户配置:
    • 注册两个应用:一个是SPA类型(对应AngularJS前端),一个是API类型(对应Web API)。
    • 给SPA应用添加API应用的权限(选择access_as_user这类自定义权限),并授予管理员同意。
    • 确保SPA应用的重定向URI和代码中配置的redirectUri一致。
  • MSAL版本选择:必须使用MSAL.js v1.x,v2及以上版本不兼容AngularJS 1.4.x的运行环境。
  • 令牌缓存:MSAL会自动处理令牌的缓存和刷新,无需手动存储令牌。

内容的提问来源于stack exchange,提问作者VenkataRatnam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 07:12:37