angular - 我想在 Angular 7+ http 调用中从 Microsoft graph 调用 Token API
问题描述
从角度应用程序我想调用https://login.microsoftonline.com/##tenant##/oauth2/v2.0/token api 从 http 调用获取访问令牌并使用我想调用的令牌https:// graph.microsoft.com/v1.0/users/##UserId##/getMemberGroups API,而不使用任何角度的npm包。
我尝试使用 http 服务,但出现以下错误
从源“https://xxx.co”访问“https://login.microsoftonline.com/xxxx/oauth2/v2.0/token”的 XMLHttpRequest 已被 CORS 策略阻止:否“访问控制允许” -Origin' 标头存在于请求的资源上。
有没有其他方法可以调用 Graph API 以获取令牌和用户获取登录用户组?
解决方案
https://login.microsoftonline.com/<tenant>/oauth2/v2.0/token
由于 CORS,不允许直接从信号页面应用程序调用。您应该将 MSAL 用于 Angular 来执行此操作。我的代码基于这个 Angular 官方演示。
请转到src/app/app.module.ts
配置您的 Azure 广告:
并首先运行这个演示。
成功运行此演示后,转到profile.component.ts
,添加以下代码:
getAccessTokenAndCallGraphAPI(){
this.authService.acquireTokenPopup({
scopes: ['GroupMember.Read.All']
}).then(result=>{
console.log("access token: "+ result.accessToken)
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Bearer '+result.accessToken
})}
const reqBody = {
"securityEnabledOnly": true
}
this.http.post("https://graph.microsoft.com/v1.0/users/<user you want to query>/getMemberGroups",reqBody,httpOptions).toPromise().then(result=>{console.log(result)});
})
}
初始化页面时调用该函数:
ngOnInit() {
this.getProfile();
this.getAccessTokenAndCallGraphAPI();
}
结果:
如果您还有其他问题,请告诉我。
推荐阅读
- java - 使用流 api java 8 映射的原始数组
- macos - Azure functions throwing error when trying to debug on MacOS
- react-native - Could not resolve all task dependencies for configuration React-navigation error
- javascript - copying a message to another channel
- node.js - Mongodb change streams getting previous values?
- flutter - 如何在购物车表中添加结帐产品并使用颤振将其保存到 firebase 中的另一个新表?
- django - Django - 在根静态文件夹中找不到静态文件,但设置指向它
- emacs - 在 emacs shell 中启用 tuareg 模式
- python - 删除重复的行,而不考虑项目顺序 pandas
- reactjs - 如何在 reactjs 中使模式可滚动