gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 05:11:10 30 4
gpt4 key购买 nike

我有 SPA Angular 应用程序登录到 Azure AD。我已关注this到目前为止的指南。

应用程序能够进行身份验证,生成一个 token ,然后将其附加到返回 .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"]],
]),
}
),
],

到目前为止,当我尝试使用我收到的 token 对 CosmosClient SDK 进行身份验证时,效果很好 用户或管理员尚未同意使用该应用程序

在 azure 广告中注册的应用程序没有获得管理员同意(这是公司政策,用户模拟应该能够授予足够的权限来访问 Cosmos DB 实例)

在后端我获取 token 如下:

            
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;
}

这给了我一个新的 token ,但是当我尝试访问该资源时,我收到了有关不同意的错误消息。有没有办法在 cosmos DB 的 BE 请求或 SPA 中给予用户同意?

编辑:征得管理员同意后,应用程序不断返回403,权限添加如下并生成 token enter image description here

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)

最佳答案

如果访问 token 没有足够的权限来执行操作,通常会出现“403 禁止”错误。

我创建了一个 Azure AD 应用程序并授予了 API 权限:

enter image description here

对于示例,我尝试使用代表流程通过Postman生成访问 token :

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

enter image description here

使用上面生成的访问 token ,我生成了访问 Cosmos DB 的 token :

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

enter image description here

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

enter image description here

Note that: To access Cosmos DB resource, you have to pass Cosmos DB API permission that is https://cosmos.azure.com/user_impersonation while generating the access token.

要解决该错误,请检查以下内容:

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

如果问题仍然存在,可能资源需要 RBAC 角色。根据您尝试访问的资源,将基于 Cosmos DB 帐户读取者角色 的角色分配给 Azure AD 应用程序:

enter image description here

关于azure - MSAL SPA + .NET API 通过 OBO 验证 cosmos DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76787888/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com