即使 ChainedTokenCredential 允许按顺序尝试多个 TokenCredential 实现,直到其中一个 getToken 方法返回访问令牌,但它只能处理身份验证错误而不能处理授权,即,它将抛出 403 错误并且不会自动切换到其他可用的身份验证,如果未定义 RBAC 权限。如果系统分配的托管身份没有 RBAC 权限,ChainedTokenCredential 不会从系统分配的托管身份切换到用户分配的托管身份
DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();
ManagedIdentityCredential userAssignedmanagedIdentityCredential = new ManagedIdentityCredentialBuilder().clientId("<USER ASSIGNED MANAGED IDENTITY CLIENT ID>").build();
ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder();
builder.addFirst(defaultAzureCredential);
builder.addLast(userAssignedmanagedIdentityCredential);
ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy();
defaultPolicy.setUserAgentSuffix(applicationName);
defaultPolicy.setPreferredRegions(Arrays.asList("Central US"));
AsyncDocumentClient asyncDocumentClient = new AsyncDocumentClient.Builder().withServiceEndpoint("<Cosmos DB URL>").withTokenCredential(builder.build()).withConnectionPolicy(defaultPolicy) .withConsistencyLevel(ConsistencyLevel.EVENTUAL).build();
下面是神器细节
<properties>
<java.version>11</java.version>
<reactor-netty>1.0.9</reactor-netty>
<reactor-core>3.4.8</reactor-core>
</properties>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core</artifactId>
<version>1.18.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-storage-blob</artifactId>
<version>12.12.0</version>
<exclusions>
<exclusion>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-cosmos</artifactId>
<version>4.17.0</version>
<exclusions>
<exclusion>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>${reactor-core}</version>
<!--$NO-MVN-MAN-VER$ -->
<!-- Please don't remove/degrade the version, possible for compatibility issues -->
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty</artifactId>
<version>${reactor-netty}</version>
<!--$NO-MVN-MAN-VER$ -->
<!-- Please don't remove/degrade the version, possible for compatibility issues -->
</dependency>