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

MSAL与Angular集成:无法使用自定义Scope仍调用Graph API求助

解决MSAL Angular使用自定义Scope而非Graph API的方案

核心配置修正

1. 调整MSAL初始化配置

修改Angular项目中的MSAL配置文件(通常是app.module.ts),将资源映射和默认Scope完全指向你的自定义API,移除所有Graph API相关配置:

export const protectedResourceMap = new Map([
  ['https://your-custom-api-domain', ['api://your-custom-api-client-id/your-custom-scope']]
]);

@NgModule({
  imports: [
    MsalModule.forRoot(
      new PublicClientApplication({
        auth: {
          clientId: 'your-angular-app-client-id',
          authority: 'https://login.microsoftonline.com/your-tenant-id',
          redirectUri: 'http://localhost:4200', // 匹配Azure门户中配置的重定向URI
        },
        cache: {
          cacheLocation: BrowserCacheLocation.LocalStorage,
          storeAuthStateInCookie: isIE,
        }
      }),
      {
        interactionType: InteractionType.Redirect,
        protectedResourceMap: protectedResourceMap
      }
    )
  ]
})

2. 请求令牌时指定自定义Scope

调用MSAL的令牌获取方法时,明确传入自定义Scope数组,避免默认请求Graph API的权限:

const tokenRequest = {
  scopes: ['api://your-custom-api-client-id/your-custom-scope']
};

this.msalService.acquireTokenSilent(tokenRequest).subscribe({
  next: (resp) => {
    // 使用resp.accessToken调用自定义Spring Boot API
  },
  error: (err) => {
    // 静默获取失败时,触发交互式登录
    this.msalService.loginRedirect(tokenRequest);
  }
});

兼容Graph令牌的替代方案(无需切换自定义Scope)

如果只是Spring Boot无法解析带nonce的令牌,先排查是否误传了ID令牌(Graph的ID令牌包含nonce,用于前端身份验证,不应传给后端API):

  • 确保Angular传递给Spring Boot的是accessToken而非idToken;
  • 若确实需要使用Graph访问令牌,可在Spring Security的JWT配置中关闭nonce校验:
@Bean
public JwtDecoder jwtDecoder() {
  NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri("https://login.microsoftonline.com/your-tenant-id/discovery/v2.0/keys").build();
  decoder.setJwtValidator(JwtValidators.createDefaultWithIssuer("https://login.microsoftonline.com/your-tenant-id/v2.0"));
  // 移除nonce验证器
  decoder.setJwtValidator(new DelegatingJwtValidator(
    Arrays.asList(
      new IssuerValidator("https://login.microsoftonline.com/your-tenant-id/v2.0"),
      new ExpirationValidator(),
      new NotBeforeValidator()
      // 排除NonceValidator
    )
  ));
  return decoder;
}

Azure门户配置校验

  • 自定义API侧:确认已在Expose an API中添加自定义Scope,且Angular应用的客户端ID已被添加到该Scope的授权列表;
  • Angular应用侧:在API permissions中移除所有Graph相关权限,仅保留自定义API的权限,并完成管理员同意(若为企业级应用)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:46:06