MS图API Oauth2PermissionGrants无法授予角色

时间:2020-04-23 19:55:19

标签: c# azure microsoft-graph-api microsoft-graph-sdks

使用以下代码,我可以首次同意给予管理员同意。 但是当我第二次调用代码时。代码返回错误。

示例:

我可以在第一个请求上授予对User.Read.All的访问权限。 但是,当我想让管理员同意担任第二个角色AccessReview.Read.All时,请求将出现以下错误

代码

 IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create("Client ID")
                .WithClientSecret("Client Secret")
                .WithTenantId("Tenant ID")
                .Build();



            string scopes = "https://graph.microsoft.com/.default";
            ClientCredentialProvider authProvider = new ClientCredentialProvider(app, scopes);
            Beta.GraphServiceClient graphClient = new Beta.GraphServiceClient(authProvider);

            Beta.OAuth2PermissionGrant test = new Beta.OAuth2PermissionGrant { ClientId = model.clientId, ConsentType = model.consentType, ExpiryTime = model.expiryTime, ResourceId = model.resourceId, Scope = model.scope };
            var response = await graphClient.Oauth2PermissionGrants
                .Request()
                .AddAsync(test);

            return response.ToString();

错误

Status Code: Conflict
Microsoft.Graph.ServiceException: Code: Request_MultipleObjectsWithSameKeyValue
Message: Permission entry already exists.
Inner error:
    AdditionalData:
    request-id: b9e44bc2-7588-4390-a3ca-9abdc213d930
    date: 2020-04-23T19:43:03
ClientRequestId: b9e44bc2-7588-4390-a3ca-9abdc213d930

2 个答案:

答案 0 :(得分:2)

您不能两次添加相同的权限授予,就像错误消息permission entry already exists一样。如果要更新权限授予,可以使用更新方法:

var oAuth2PermissionGrant = new OAuth2PermissionGrant
{
    Scope = "scope-value"
};

await graphClient.OAuth2Permissiongrants["{id}"]
    .Request()
    .UpdateAsync(oAuth2PermissionGrant);

参考:

https://docs.microsoft.com/en-us/graph/api/oauth2permissiongrant-update?view=graph-rest-beta&tabs=http

答案 1 :(得分:1)

我发现了问题。 Graph API根据同意类型为Oauth Grant权限创建单个对象。 因此,对于第一个请求,请调用发布请求以授予访问权限。 但是对于第二个请求,请使用patch命令更新对象

var oAuth2PermissionGrant = new OAuth2PermissionGrant
{
    Scope = "scope-value"
};

await graphClient.OAuth2Permissiongrants["{id}"]
    .Request()
    .UpdateAsync(oAuth2PermissionGrant);

注意: 在patch命令中添加已授予访问权并希望授予访问权限的范围。 如果仅添加要授予访问权限的范围,则先前的范围授予访问权限将被撤消,只有新角色才具有授予访问权限。