0
点赞
收藏
分享

微信扫一扫

【Azure Developer】使用Microsoft Graph API创建用户时候遇见“401 : Unauthorized”“403 : Forbidden”

问题描述

编写Java代码调用Mircrosoft Graph API创建用户时,分别遇见了“401 : Unauthorized”和“403 : Forbidden”错误,调用的Java代码片段如下:

选择 Microsoft Graph 身份验证

ClientCredentialProvider authProvider = newNationalCloud.Global);

创建用户

IGraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();

User user = new User();
user.accountEnabled = true;
user.displayName = "Adele Vance";
user.mailNickname = "AdeleV";
user.userPrincipalName = "AdeleV@contoso.onmicrosoft.com";
PasswordProfile passwordProfile = new PasswordProfile();
passwordProfile.forceChangePasswordNextSignIn = true;
passwordProfile.password = "xWwvJ]6NMw+bWH-d";
user.passwordProfile = passwordProfile;

graphClient.users()
.buildRequest()
.post(user);

 

解决办法

401:Unauthorized

因在代码中使用的环境为NationalCloud.Global,所以需要修改为NationalCloud.China。开启Debug模式,在对象graphClient中,发现Post请求的URL地址为​​https://graph.microsoft.com/v1.0/users​​​, 而这个地址为Global环境的Endpoint,需要修改为中国区的地址:​​https://microsoftgraph.chinacloudapi.cn/v1.0/users​​。

修改后的代码为:

ClientCredentialProvider authProvider = new  NationalCloud.China);= GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();

User user = new User();
user.accountEnabled = true;
user.displayName = "Adele Vance";
user.mailNickname = "AdeleV";
user.userPrincipalName = "AdeleV@contoso.onmicrosoft.com";
PasswordProfile passwordProfile = new PasswordProfile();
passwordProfile.forceChangePasswordNextSignIn = true;
passwordProfile.password = "xWwvJ]6NMw+bWH-d";
user.passwordProfile =graphClient.setServiceRoot("https://microsoftgraph.chinacloudapi.cn/v1.0");

403 : Forbidden

因为创建用户需要对应的AAD授权,查看创建用户文档资料中,说明必须具有以下的授权:

【Azure Developer】使用Microsoft Graph API创建用户时候遇见“401 : Unauthorized”“403 : Forbidden”_microsoft

 

所以可以在AAD Application中查看当前的API Permission是否包含并被授予权限。如下图中,虽然包含了权限,但没有被Admin授予权限

【Azure Developer】使用Microsoft Graph API创建用户时候遇见“401 : Unauthorized”“403 : Forbidden”_ide_02

 

所以在调用创建用户接口时,会抛出如下的错误

【Azure Developer】使用Microsoft Graph API创建用户时候遇见“401 : Unauthorized”“403 : Forbidden”_Azure Developer_03

 

参考资料

创建用户:​​https://docs.microsoft.com/zh-cn/graph/api/user-post-users?view=graph-rest-1.0&tabs=java#example​​

根据应用场景选择 Microsoft Graph 身份验证提供程序:​​https://docs.microsoft.com/zh-cn/graph/sdks/choose-authentication-providers?tabs=Java#client-credentials-provider​​

Grant an appRoleAssignment to a user:​​https://docs.microsoft.com/en-us/graph/api/user-post-approleassignments?view=graph-rest-1.0&tabs=http​​

权限:​​https://docs.microsoft.com/zh-cn/graph/api/user-post-users?view=graph-rest-1.0&tabs=http#permissions​​

 

当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!



举报

相关推荐

0 条评论