MSAL-即使未在“ API权限”中配置应用程序也可以请求权限

时间:2020-06-02 07:17:38

标签: .net-core azure-active-directory identityserver3 msal

我使用MSAL库创建了一个小型的.NET Core 3.1控制台应用程序,该应用程序请求范围api://55a047a1-a0d1-4b6b-9896-751a848e1e06/testscope2

自定义API有两个作用域

  • api:// 55a047a1-a0d1-4b6b-9896-751a848e1e06 / testscope1
  • api:// 55a047a1-a0d1-4b6b-9896-751a848e1e06 / testscope2

enter image description here

我还在Azure Active Directory中配置了另一个名为test-app的应用程序,它代表我的控制台应用程序。

我为此应用程序仅配置了一个API权限(api://55a047a1-a0d1-4b6b-9896-751a848e1e06/testscope1)。我的理解是,使用此配置后,客户端应用将只能请求范围test1,而不允许test-app请求范围scope2

下面是屏幕截图

enter image description here

这是我的代码:

//<PackageReference Include="Microsoft.Identity.Client" Version="4.13.0" />
namespace console_client
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Azure AD parameters
            var clientId = "dddeefa5-d95c-4931-a53d-2382deee27c3";
            var tenant = "-- MY TENANT ID--";
            var instance = "https://login.microsoftonline.com/";
            #endregion

            var client = PublicClientApplicationBuilder
                .Create(clientId)
                .WithDefaultRedirectUri()
                .WithAuthority($"{instance}{tenant}")
                .Build();

            List<string> scopes = new List<string>();

            try
            {
                // I was under impression that this call will throw as exception as
                // this app is requesting 'testscope2' which is not included in API Permissions
                // while configuring test-app in Azure Active Directory (dddeefa5-d95c-4931-a53d-2382deee27c3 )
                // But I was able to retrieve token back with testscope2 in it.
                scopes.Add("api://55a047a1-a0d1-4b6b-9896-751a848e1e06/testscope2");
                var authenticationResult = client.AcquireTokenInteractive(scopes).ExecuteAsync().Result;
                Console.WriteLine($"Interactive Access token is : {authenticationResult.AccessToken}");
            }
            catch (Exception ex)
            { 
                System.Console.WriteLine($"******* {ex.Message}");
            }
        }
    }
}

问题

我错过了什么吗?为什么即使该应用未配置权限,我仍要找回访问令牌?

谢谢

1 个答案:

答案 0 :(得分:2)

TL; DR这是一个功能。

使用v2端点/ MSAL,您可以请求未在应用清单中定义的范围。 应用程序注册中的权限是应用程序所需的 static 权限。 但是您的应用程序也可以在登录时请求 dynamic 权限。 当然,用户/管理员仍然需要同意这一点,未经同意,应用程序将不会获得许可。

您的应用似乎是一个单租户应用,因此这对您并没有真正的改变。 它主要用于多租户SaaS应用程序,这些应用程序可能需要在应用程序注册/清单中要求最低的权限,然后根据需要为选择启用功能请求更多权限。

顺便说一句,如果要使用在应用程序注册中定义的权限,则可以请求特殊范围:api://55a047a1-a0d1-4b6b-9896-751a848e1e06/.default(您的应用程序ID URI或客户端ID +“ /。default”)。 这将使AAD查看您的应用程序注册,以确定检查同意的权限。