首页 > 解决方案 > “MSAL”:发行者无效

问题描述

我正在从 ADAL 迁移到 MSAL。

我在 angular 8 中添加了以下配置:

MsalModule.forRoot({
      auth: {
          clientId: "xxxxx",
          authority: "https://login.microsoftonline.com/tenant",
                validateAuthority: true,
                redirectUri: window.location.href,
                postLogoutRedirectUri: "http://localhost:4200/",
                navigateToLoginRequestUrl: true
      },
      cache: {
        cacheLocation: 'localStorage',
        storeAuthStateInCookie: isIE, // set to true for IE 11
      },
    },
    {
      popUp: false,
      consentScopes: ['Directory.AccessAsUser.All',
        'user.read',
        'openid',
        'profile',
        'User.ReadWrite',
        'User.ReadBasic.All',
        'User.Read.All',
        'Group.Read.All',
        'Directory.AccessAsUser.All'
      ],
      unprotectedResources: ['https://www.microsoft.com/en-us/'],
      protectedResourceMap,
      extraQueryParameters: {}
  }),

我也试图通过获取令牌来验证

const loginRequest = {
    scopes: ['user.read','openid', 'profile'],
  };

 this.authService.acquireTokenSilent(loginRequest);

                   this.broadcastService.subscribe("msal:acquireTokenFailure", (payload) => {
                    console.info("acquire token failure " + JSON.stringify(payload));
                  });
                 this.broadcastService.subscribe("msal:acquireTokenSuccess", (payload) => {
                    console.info("acquire token success " + JSON.stringify(payload));
                  });

在 .net 方面,我编写了以下代码:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                AuthenticationOptions authSettings = Configuration.GetSection("AzureAd").Get<AuthenticationOptions>();


                options.Authority = authSettings.Authority;
                options.SaveToken = true;
                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {

                        // Add the access_token as a claim, as we may actually need it
                        if (context.SecurityToken is JwtSecurityToken accessToken)
                        {
                            if (context.Principal.Identity is ClaimsIdentity identity)
                            {
                                identity.AddClaim(new Claim("access_token", accessToken.RawData));
                            }
                        }

                        return Task.CompletedTask;
                    },
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) &&
                            ((path.StartsWithSegments(SignalRHub) || path.StartsWithSegments(QuillHub))))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }

                        return Task.CompletedTask;
                    }
                };

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    //Both the client id and app id URI of this API should be valid audiences
                    ValidAudiences = new List<string> { authSettings.ClientId },
                };
            });

但是,当我尝试点击令牌时,我会获得令牌成功,但在 api 方面我收到错误消息,指出发行者“ https://login.microsoftonline.com/tenantid/v2.0 ”无效

我做错了什么?

标签: angularasp.net-coremsal

解决方案


听起来您的后端配置了 v1 权限,但您获得的是 v2 令牌。将 API 配置中的权限更改为:

https://login.microsoftonline.com/tenant/v2.0

啊,实际上这可能还不够。看起来您的前端正在获取 Microsoft Graph API 的访问令牌。您需要为您的 API 获取令牌,而不是 MS Graph API。为此,请指定在您的 API 应用注册的公开 API 页面中注册的一个或多个范围。

完成此操作后,您可能会再次获得 v1 令牌。因此,在更改权限之前先执行此操作。


推荐阅读