无法在 Azure AD B2C 实施的控制器内部的 ASP.NET Core MVC 示例代码中获取访问令牌

问题描述 投票:0回答:1

我们正在探索微软提供的用于实现“Azure AD B2C 身份验证”的代码示例。我们正在使用来自“https://learn.microsoft.com/en-us/azure/active-directory-b2c/integrate-with-app-code-样本”,第 4 个样本,名称为

dotnetcore-webapp-msal-api
.

以下是我们正在努力实现的目标:

  1. 在控制器中获取访问令牌。
  2. 根据声明中的角色显示菜单项。

任何输入都会有所帮助。

提前致谢。

我通过进行必要的更改尝试了 Microsoft 提供的示例代码,但我无法访问令牌。参考以下代码:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Web;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using WebApp_OpenIDConnect_DotNet.Models;

namespace WebApp_OpenIDConnect_DotNet.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private readonly ITokenAcquisition tokenAcquisition;

        public HomeController(ITokenAcquisition tokenAcquisition)
        {
            this.tokenAcquisition = tokenAcquisition;
        }

        public async Task<IActionResult> Index()
        {
            // Getting Token
            string accessToken = await this.tokenAcquisition.GetAccessTokenForAppAsync("https://<Domain>.<Tenant ID of the web api>/access_as_user");
            return View();
        }

        [AllowAnonymous]
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

你期望发生什么?获取“访问”令牌。

究竟发生了什么?请参考

Index
方法

我无法获得访问令牌。当我检查变量

accessToken
中的详细信息时,出现以下异常:

InnerException = {“IDW10404:'scope'参数的格式应为'AppIdUri/.default'。请参阅https://aka.ms/ms-id-web/daemon-scenarios。(参数'scope') "}

azure-active-directory azure-ad-b2c msal
1个回答
0
投票

我试图重现错误:

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    var initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');


    services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)

       .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
           .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
                .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
               .AddInMemoryTokenCaches();


    services.AddControllersWithViews(options =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
    });
   services.AddRazorPages()
        .AddMicrosoftIdentityUI();
}

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.


  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            IdentityModelEventSource.ShowPII = true;
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

        app.UseRouting();
        
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });
        
        }

error: 'invalid_client', error_description: 'AADSTS650053: The application 'app' asked for scope 'User.Read''' that doesn't exist on the resource xxxx.

Appsettings.json

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    // "Authority": "https://login.microsoftonline.com/xxx",
    "Domain": "xxx.onmicrosoft.com",
    "ClientId": "xx",
    "TenantId": "xxx18f3b0",
    "ClientSecret": "xxx",
    "CallbackPath": "/signin-oidc"
  },
  "DownstreamApi": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
//    "Scopes": "api://xxxx/access_as_user"
    "Scopes": "api://xxx/.default"
  },

你得到的错误

  "IDW10404: 'scope' parameter should be of the form 'AppIdUri/.default' is due to scope being incorrect format.

必须是"Scopes": "api://xxx/.default"

像 api:///.default 即;

<AppIdUri>/.default

AppId uri,您可以在门户中查看:

如果您正在调用 Microsoft Graph API,

Scope 必须是 "Scopes":

https://graph.microsoft.com/.default

Appsettings.json

  {
      "AzureAd": {
        "Instance": "https://login.microsoftonline.com/",
        "Domain": "xxxx.onmicrosoft.com",
        "ClientId": "xxx",
        "TenantId": "xxx",
        "ClientSecret": "xxxx",
        "CallbackPath": "/signin-oidc"
      },
      "DownstreamApi": {
        "BaseUrl": "https://graph.microsoft.com/v1.0",
        "Scopes": "https://graph.microsoft.com/.default",
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*"
    }

必须像

代码:

string appScope = "appIdUri/.default";
string accessToken = await this.tokenAcquisition.GetAccessTokenForAppAsync(appScope);
 

© www.soinside.com 2019 - 2024. All rights reserved.