错误:由于对用户的挑战而抛出了msaluirequiredException

发布于 2025-02-13 19:36:52 字数 1506 浏览 0 评论 0原文

我正在尝试进行基本的Microsoft Graph API调用,但是每当我调用getAccessTokenForuserAsync()函数以获取令牌时,我会收到此错误。这是ASP.NET Core 6 MVC应用程序。

program.cs:

JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
        .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
        .AddInMemoryTokenCaches();

appsettings.json:

"MicrosoftGraph": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "user.read"
},

控制器:

[AuthorizeForScopes(Scopes = new string[] { "user.read" })]
public class UserManagementController : Controller
{
    ...
    [AuthorizeForScopes(Scopes = new string[] { "user.read" })]
    public async Task<IActionResult> Index()
    {
        try
        {
             var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "user.read" });
             return View();
        }
        catch(Exception ex)
        {
            return BadRequest("An error occurred loading the user management page.");
        }
    }
}

我尝试过许多解决方案。错误总是相同的:

由于用户面临挑战,因此抛出了msaluirequiredException。没有帐户或登录提示传递给AccelireTokenSilent Call

我只是想让基本知识正常工作,没有任何幻想。

I am attempting to make a basic Microsoft Graph API call but I get this error whenever I call the GetAccessTokenForUserAsync() function to get a token. This is an ASP.NET Core 6 MVC application.

Program.cs:

JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
        .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
        .AddInMemoryTokenCaches();

appSettings.json:

"MicrosoftGraph": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "user.read"
},

Controller:

[AuthorizeForScopes(Scopes = new string[] { "user.read" })]
public class UserManagementController : Controller
{
    ...
    [AuthorizeForScopes(Scopes = new string[] { "user.read" })]
    public async Task<IActionResult> Index()
    {
        try
        {
             var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "user.read" });
             return View();
        }
        catch(Exception ex)
        {
            return BadRequest("An error occurred loading the user management page.");
        }
    }
}

I've tried many solutions to this. The error is always the same:

An MsalUiRequiredException was thrown due to a challenge for the user. No account or login hint was passed to the AcquireTokenSilent call

I'm just trying to get the basics working, nothing fancy.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北风几吹夏 2025-02-20 19:36:52

请让我在这里分享一个例子。

首先,让我们添加MS Identity UI,创建一个名为_loginPartial.cshtml in views/sharone文件夹中的部分视图。

@using System.Security.Principal

<ul class="navbar-nav">
@if (User.Identity.IsAuthenticated)
{
        <li class="nav-item">
            <span class="navbar-text text-dark">Hello @User.Identity.Name!</span>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a>
        </li>
}
else
{
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a>
        </li>
}
</ul>

然后将部分视图添加到_Layout.cshtml&lt; partial name =“ _ loginPartial”/&gt;

“在此处输入图像描述”

然后在program.cs.cs中,通过设置Azure Ad agentication以下代码,并在app.useeauthorization();之前添加app.useateentication();

string[]? initialScopes = builder.Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
        .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
        .AddInMemoryTokenCaches();
// Add services to the container.
builder.Services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI(); 

这些需要以下包装:

<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.6" />
<PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="1.25.1" />
<PackageReference Include="Microsoft.Identity.Web.UI" Version="1.25.1" />

然后appSettings.json,添加类似下面的属性:

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "tenant_name.onmicrosoft.com",
    "TenantId": "common",
    "ClientId": "azure_ad_client_id",
    "ClientSecret": "client_secret",
    "CallbackPath": "/signin-oidc"
  },
  "DownstreamApi": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "user.read"
  }

然后添加[授权]为HOME Con​​troller添加,以便您在渲染索引页面之前要求您登录。

[Authorize]
public class HomeController : Controller
{
    private readonly ITokenAcquisition _tokenAcquisition;

    public HomeController(ITokenAcquisition tokenAcquisition)
    {
        _tokenAcquisition = tokenAcquisition;
    }

    [AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
    public async Task<IActionResult> IndexAsync()
    {
        string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "user.read" });
        return View();
    }
}

Pls allow me share an example here.

At first, let's adding ms identity ui, create a partial view named _LoginPartial.cshtml in Views/Shared folder.

@using System.Security.Principal

<ul class="navbar-nav">
@if (User.Identity.IsAuthenticated)
{
        <li class="nav-item">
            <span class="navbar-text text-dark">Hello @User.Identity.Name!</span>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a>
        </li>
}
else
{
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a>
        </li>
}
</ul>

Then adding the partial view into _Layout.cshtml : <partial name="_LoginPartial" />

enter image description here

Then in the Program.cs, set the azure ad authentication by following code, and adding app.UseAuthentication(); before app.UseAuthorization();:

string[]? initialScopes = builder.Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
        .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
        .AddInMemoryTokenCaches();
// Add services to the container.
builder.Services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI(); 

These require following packages:

<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.6" />
<PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="1.25.1" />
<PackageReference Include="Microsoft.Identity.Web.UI" Version="1.25.1" />

Then in appsettings.json, adding properties like below:

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "tenant_name.onmicrosoft.com",
    "TenantId": "common",
    "ClientId": "azure_ad_client_id",
    "ClientSecret": "client_secret",
    "CallbackPath": "/signin-oidc"
  },
  "DownstreamApi": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "user.read"
  }

Then adding [Authorize] for the home controller so that it will ask you to sign in before rendering index page.

[Authorize]
public class HomeController : Controller
{
    private readonly ITokenAcquisition _tokenAcquisition;

    public HomeController(ITokenAcquisition tokenAcquisition)
    {
        _tokenAcquisition = tokenAcquisition;
    }

    [AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
    public async Task<IActionResult> IndexAsync()
    {
        string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "user.read" });
        return View();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文