从Web API发送Graph API邀请(POST请求)工作正常,在Angular应用程序中使用它失败



当我通过Postman向用户发送Graph API邀请时,用户会通过电子邮件获得邀请Url。

这就是我实例化GraphClientService-API代码的方式:

var tokenProvider = new AzureServiceTokenProvider();
string token = tokenProvider.GetAccessTokenAsync("https://graph.microsoft.com", "tenant-id-mqksmlsqdkjf").GetAwaiter().GetResult(); 
_graphServiceClient = new GraphServiceClient(
new DelegateAuthenticationProvider(x =>
{
x.Headers.Authorization = new AuthenticationHeaderValue(
"Bearer", token);
return Task.FromResult(0);
}));

发布请求-API代码:

var invitation = new Invitation()
{
InvitedUserEmailAddress = data["email"].ToString(),
InviteRedirectUrl = Configuration["AzureAd:urlFrontEnd"],
SendInvitationMessage = true
};
await _graphServiceClient.Invitations
.Request()
.AddAsync(invitation);
return Ok("Invitation sent to " + data["email"].ToString());

请求后消耗-角度/前端代码:

inviteUser() {
const body = JSON.stringify(
{
"email": "user@mail.com"
}
);
this.http.post('https://apiUrl.azurewebsites.net/api/user/invite', body, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Bearer ' + localStorage.getItem('jwt')
})
}).subscribe(response => {
this.router.navigate(['/']);
}, err => {
this.errorMessage = 'Invalid Email or Password.';
});
}

在前端调用相同的Post Request失败,并显示消息:

"代码:未经授权\r\n消息:权限不足,无法执行应用程序请求的操作"0000000 3-0000-0000-c000-000000000000"。ControllerName=MSGraphInviteAPI,ActionName=CreateInvite,URL绝对值路径=/api/">

我将"未经授权"设为粗体,因为我已登录并且页面上应用了CanActivate-AuthGuard。因此,我被授权+我在Post Request的标头中分配我的Bearer令牌。

在Azure门户中,我注册了Web API和前端应用程序(Azure AD(。我在两个应用程序(Directory.ReadWrite.All,User.Invite.All和User.ReadWrite.All(中添加了必要作用域的权限。除此之外,我还授予了管理员同意。。。

更改实例化GraphClientService的方式完成了这项工作。SigninKey的验证是真的,所以我也必须提供这个

string authority = "https://login.microsoftonline.com/{0}";
string graphResourceId = "https://graph.microsoft.com";
string tenantId = Configuration["AzureAd:TenantId"];
string clientId = Configuration["AzureAd:ClientId"];
string secret = Configuration["AzureAd:SigninKey"];
authority = String.Format(authority, tenantId);
AuthenticationContext authContext = new AuthenticationContext(authority);
var accessToken = authContext.AcquireTokenAsync(graphResourceId, new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, secret)).Result.AccessToken;
_graphServiceClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
requestMessage =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
return Task.FromResult(0);
}));

我还在FE中使用存储库服务,在发送POST请求时添加必要的头

inviteUser() {
const body = JSON.stringify(
{
email: 'user@email.com'
}
);
this.repoService.create('api/user/invite', body)
.subscribe(res => { ...
},
(error => { ...
})
);
}

相关内容

最新更新