azure MSAL SPA + .NET API通过OBO认证cosmos DB

q1qsirdb  于 2023-08-07  发布在  .NET
关注(0)|答案(1)|浏览(103)

我有SPA Angular应用程序登录到Azure AD。到目前为止,我已经遵循了this指南。
应用程序能够进行身份验证,生成一个令牌,然后将其附加到返回到.NET API的请求中。
Msal模块声明如下:

MsalModule.forRoot(
            new PublicClientApplication({
                auth: {
                    clientId: "obscured9",
                    authority:
                        "obscured",
                    redirectUri: "http://localhost:4200",
                },
                cache: {
                    cacheLocation: "localStorage",
                    storeAuthStateInCookie: isIE,
                },
            }),
            {
                interactionType: InteractionType.Popup,
                authRequest: {
                    scopes: ["access_as_user"],
                },
            },
            {
                interactionType: InteractionType.Popup, // MSAL Interceptor Configuration
                protectedResourceMap: new Map([
                    ["Enter_the_Graph_Endpoint_Here/v1.0/me", ["user.read"]],
                    ["https://localhost:7162", ["api://obscured/API"]],
                ]),
            }
        ),
    ],

字符串
到目前为止,当我尝试使用接收到的The user or administrator has not consented to use the application with令牌向CosmosClientSDK进行身份验证时,这一方法运行良好
Azure广告中注册的应用程序没有管理员同意(这是公司的政策,用户模拟应该能够授予足够的权限来访问cosmos DB示例)
在后端,我得到的令牌如下:

var token = _tokenResolver.GetToken(); //Token from SPA
            string[] scopes = { "access_as_user" };

            string appKey = "obscured";
            string clientId = "obscured";

            var app = ConfidentialClientApplicationBuilder.Create(clientId)
                .WithClientSecret(appKey)
                .WithTenantId("obscured")
                .Build();
            UserAssertion userAssertion = new UserAssertion(token, 
                "urn:ietf:params:oauth:grant-type:jwt-bearer");
            var result = app.AcquireTokenOnBehalfOf(scopes, userAssertion).ExecuteAsync().Result;
            // base64 encode
            var token2 = Convert.ToBase64String(Encoding.UTF8.GetBytes(result.AccessToken));
            var credentials = new AzureKeyCredential(Convert.ToBase64String(Encoding.UTF8.GetBytes(token2)));
            _cosmosClient = new CosmosClient("obscured",
                credentials,
                new CosmosClientOptions
                {
                    AllowBulkExecution = true,
                    ApplicationName = "obscured",
                    ConnectionMode = ConnectionMode.Direct,
                    ConsistencyLevel = ConsistencyLevel.Session,
                    RequestTimeout = new TimeSpan(0,
                        0,
                        400),
                    Serializer = serializer,
                    MaxRetryAttemptsOnRateLimitedRequests = 10,
                    MaxRetryWaitTimeOnRateLimitedRequests = new TimeSpan(0,
                        0,
                        120)
                });

            // ensure created
            await CreateDatabaseAndContainerIfNotExistsAsync();

            _isLoaded = true;
        }


这给了我一个新的令牌,但是当我试图访问资源时,我收到了关于不同意的错误消息。是否有一种方法可以在BE请求中或在cosmos DB的SPA中给予用户同意?
编辑:在获取管理员同意后,应用程序继续返回403,权限添加如下,令牌生成

System.AggregateException: One or more errors occurred. (Response status code does not indicate success: Forbidden (403); Substatus: 5301; ActivityId: bc1f49a1-4398-4610-8e51-539cb9a65fa7; Reason: (Request blocked by Auth upodi : Request is blocked because principal [5c4d3d80-546b-471b-bba3-de92008fc398] does not have required RBAC permissions to perform action [Microsoft.DocumentDB/databaseAccounts/readMetadata] on resource [/]. Learn more: https://aka.ms/cosmos-native-rbac.
ActivityId: bc1f49a1-4398-4610-8e51-539cb9a65fa7, Microsoft.Azure.Documents.Common/2.14.0, Windows/10.0.22621 cosmos-netstandard-sdk/3.30.8);)
 ---> Microsoft.Azure.Cosmos.CosmosException : Response status code does not indicate success: Forbidden (403); Substatus: 5301; ActivityId: bc1f49a1-4398-4610-8e51-539cb9a65fa7; Reason: (Request blocked by Auth upodi : Request is blocked because principal [5c4d3d80-546b-471b-bba3-de92008fc398] does not have required RBAC permissions to perform action [Microsoft.DocumentDB/databaseAccounts/readMetadata] on resource [/]. Learn more: https://aka.ms/cosmos-native-rbac.
ActivityId: bc1f49a1-4398-4610-8e51-539cb9a65fa7, Microsoft.Azure.Documents.Common/2.14.0, Windows/10.0.22621 cosmos-netstandard-sdk/3.30.8);
   at Microsoft.Azure.Cosmos.GatewayStoreClient.ParseResponseAsync(HttpResponseMessage responseMessage, JsonSerializerSettings serializerSettings, DocumentServiceRequest request)
   at Microsoft.Azure.Cosmos.GatewayAccountReader.GetDatabaseAccountAsync(Uri serviceEndpoint)
   at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetAccountPropertiesHelper.GetAndUpdateAccountPropertiesAsync(Uri endpoint)
   at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetAccountPropertiesHelper.GetAccountPropertiesAsync()
   at Microsoft.Azure.Cosmos.GatewayAccountReader.InitializeReaderAsync()
   at Microsoft.Azure.Cosmos.CosmosAccountServiceConfiguration.InitializeAsync()
   at Microsoft.Azure.Cosmos.DocumentClient.InitializeGatewayConfigurationReaderAsync()
   at Microsoft.Azure.Cosmos.DocumentClient.GetInitializationTaskAsync(IStoreClientFactory storeClientFactory)
   at Microsoft.Azure.Documents.BackoffRetryUtility`1.ExecuteRetryAsync[TParam,TPolicy](Func`1 callbackMethod, Func`3 callbackMethodWithParam, Func`2 callbackMethodWithPolicy, TParam param, IRetryPolicy retryPolicy, IRetryPolicy`1 retryPolicyWithArg, Func`1 inBackoffAlternateCallbackMethod, Func`2 inBackoffAlternateCallbackMethodWithPolicy, TimeSpan minBackoffForInBackoffCallback, CancellationToken cancellationToken, Action`1 preRetryCallback)
   at Microsoft.Azure.Documents.ShouldRetryResult.ThrowIfDoneTrying(ExceptionDispatchInfo capturedException)
   at Microsoft.Azure.Documents.BackoffRetryUtility`1.ExecuteRetryAsync[TParam,TPolicy](Func`1 callbackMethod, Func`3 callbackMethodWithParam, Func`2 callbackMethodWithPolicy, TParam param, IRetryPolicy retryPolicy, IRetryPolicy`1 retryPolicyWithArg, Func`1 inBackoffAlternateCallbackMethod, Func`2 inBackoffAlternateCallbackMethodWithPolicy, TimeSpan minBackoffForInBackoffCallback, CancellationToken cancellationToken, Action`1 preRetryCallback)
   at Microsoft.Azure.Cosmos.AsyncCacheNonBlocking`2.GetAsync(TKey key, Func`2 singleValueInitFunc, Func`2 forceRefresh)
   at Microsoft.Azure.Cosmos.AsyncCacheNonBlocking`2.GetAsync(TKey key, Func`2 singleValueInitFunc, Func`2 forceRefresh)
   at Microsoft.Azure.Cosmos.DocumentClient.EnsureValidClientAsync(ITrace trace)

1zmg4dgp

1zmg4dgp1#

如果访问令牌没有足够的权限执行操作,则通常会发生 “403 forbidden”错误。
我创建了一个Azure AD应用,并授予了API权限:
x1c 0d1x的数据
对于 * 示例 *,我尝试使用On-Behalf-Of流程通过 Postman 生成访问令牌:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

client_id:ClientID
grant_type:authorization_code
scope:api://ClientID/access_as_user
code:code
redirect_uri:https://jwt.ms
client_secret:-ClientSecret

字符串



使用上面生成的访问令牌,我生成了访问Cosmos DB的令牌

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

client_id:ClientID
client_secret:ClientSecret
scope:https://cosmos.azure.com/user_impersonation
grant_type:urn:ietf:params:oauth:grant-type:jwt-bearer
assertion:
requested_token_use:on_behalf_of



当我解码访问令牌时,Cosmos DB范围存在如下所示:


注意:要访问Cosmos DB资源,需要在生成访问令牌时传递Cosmos DB API权限**https://cosmos.azure.com/user_impersonation**。
**若要解决此错误,**请检查以下内容:

  • 解码jwt.ms: Welcome!中的访问令牌,检查aud是否为https://cosmos.azure.comscp是否为user_impersonation
  • 修改代码,获取Cosmos DB访问令牌时,将scope传递为**https://cosmos.azure.com/user_impersonation**,如下所示:
string[] scopes = { "https://cosmos.azure.com/user_impersonation" }

  • 如果问题仍然存在,* 可能资源需要RBAC角色。根据您尝试访问的资源,将基于角色的(如**Cosmos DB Account Reader Role**)分配给Azure AD应用程序:

x1c4d 1x的

相关问题