草庐IT

c# - Azure AD 异常 - AADSTS50105 - "The signed in user is not assigned to a role for the application"

coder 2024-06-03 原文

我正在使用 Azure AD 为 ASP.NET Web API 2 REST API 设置身份验证。我希望所有客户端都能够使用用户名和密码通过 REST API 进行身份验证。我已经设置了 Azure AD(下面是完整的步骤,但本质上是 - 创建目录、添加用户、添加应用程序、在 list 中向应用程序添加角色、将用户分配给应用程序)。但是,当我尝试通过控制台应用程序(底部的完整代码)进行测试时,出现异常:

类型为“Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException”的未处理异常发生在 Microsoft.IdentityModel.Clients.ActiveDirectory.dll 中

其他信息:AADSTS50105:登录用户“test@azureadwebapitest.onmicrosoft.com”未分配给应用程序“8ed6bbe9-dce7-4bed-83af-aa5472ac4eef”的角色。

我猜需要在 list 中进行一些调整,但我不知道。

代码如下:

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;

namespace WebApiClientTest
{
    class Program
    {
        static void Main(string[] args)
        {
            const string authorityUri = "https://login.microsoftonline.com/azureadwebapitest.onmicrosoft.com/";
            const string resource = "https://azureadwebapitest.onmicrosoft.com/test";
            const string clientId = "8ed6bbe9-dce7-4bed-83af-aa5472ac4eef";
            const string userId = "test@azureadwebapitest.onmicrosoft.com";
            const string password = "[REMOVED for StackOverflow post]";

            UserCredential credentials = new UserCredential(userId, password);
            AuthenticationContext context = new AuthenticationContext(authorityUri);
            var authresult = context.AcquireToken(resource, clientId, credentials);
            Console.WriteLine("Access token: {0}", authresult.AccessToken);
            Console.ReadLine();
        }
    }
}

下面是完整的重现步骤:

<强>1。创建新的 Azure AD 目录:

<强>2。添加新应用:

<强>3。将“访问应用程序所需的用户分配”设置为"is"。设置“读取目录数据”应用程序权限。复制客户端 ID。保存:

<强>4。下载 list 。编辑 list 并添加两个角色。上传 list :

<强>5。从步骤 1 返回目录并添加用户

6.打开新浏览器到https://account.activedirectory.windowsazure.com/并以用户身份登录。更改密码。注意没有可用的应用程序:

7.返回经典门户。将用户分配给 Application 中的 generalclient 角色。请注意,用户现在已分配给应用程序

<强>8。返回用户帐户门户并刷新。您可能需要刷新几次或四处点击。注意应用程序现在显示

  1. 看来,设置应该已经完成​​了。

  2. 创建一个新的控制台应用程序。

  3. 安装 Nuget 包“Microsoft.IdentityModel.Clients.ActiveDirectory”

  4. 将代码复制到控制台应用程序(文章顶部),将您的密码插入“密码”字符串,然后开始调试:

结果:

类型为“Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException”的未处理异常发生在 Microsoft.IdentityModel.Clients.ActiveDirectory.dll 中

其他信息:AADSTS50105:登录用户“test@azureadwebapitest.onmicrosoft.com”未分配给应用程序“8ed6bbe9-dce7-4bed-83af-aa5472ac4eef”的角色。

预期结果:

访问 token 被写入控制台输出。

最佳答案

对我有用:

将属性 User assignment required? 值更改为 No 对我有用。这可以在 Enterprise application --> Name of your registered application --> Properties

下找到

关于c# - Azure AD 异常 - AADSTS50105 - "The signed in user is not assigned to a role for the application",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37062964/

有关c# - Azure AD 异常 - AADSTS50105 - "The signed in user is not assigned to a role for the application"的更多相关文章

随机推荐