azure - Microsoft 从 oauth2 登录问题

标签 azure reactjs authentication oauth-2.0 axios

我有一个使用 axios 库来处理请求的 React 应用程序。因此,请遵循下一篇文章:

How to login with username/password using OAuth2 and microsoft login and HTTP request

我可以对 Postman 执行该操作。

然后我设置 axios 库来执行 POST

const dataForBody = `${'grant_type=password&' +
      'username='}${encodeURI(userName)}&` +
      `password=${encodeURI(userPassword)}&` +
      `client_id=${encodeURI(clientID)}&` +
      `resource=${encodeURI('https://graph.microsoft.com')}&` +
      `client_secret=${encodeURI(clientSecret)}`;
const messageHeaders = {
  'Content-Type': 'application/x-www-form-urlencoded'
};

axios({
  method: 'post',
  url: 'https://login.microsoftonline.com/{tenant}/oauth2/token',
  headers: messageHeaders,
  data: dataForBody,
})
  .then((response) => {

  });

但我收到以下错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://login.microsoftonline.com/{tenant}/oauth2/token. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

我尝试添加:

'Access-Control-Allow-Origin': 'https://login.microsoftonline.com',

到标题,但它不起作用。

因此添加 Allow-Control-Allow-Origin: *​​​ chrome 扩展解决了我的问题。

问题是,我的应用程序要在 azure 上发布,所以我在其他网络浏览器上测试了该请求,但它不起作用。所以我不希望我的用户安装该扩展。

我的请求有问题吗?为什么postman不用设置header就可以做到?

还有其他方法可以实现吗?

PS:我读到了有关使用 adal.js 的信息,但我不想使用微软的登录屏幕,因为我知道应用程序的用户和通行证,并且我想避免手动登录。

最佳答案

您面临的问题是由于您尝试通过 AJAX 调用 token 端点,但由于缺少 CORS header ,它不会接受该端点。您无法添加它,Azure AD 的响应中缺少它。

您需要做的是,您必须使用 OAuth 隐式授予流程,而不是从 token 端点获取访问 token 。此流程允许您直接在授权阶段获取 token ,并且专为基于 JavaScript 的应用程序设计。更多信息请点击:https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-dev-understanding-oauth2-implicit-grant .

这意味着您无法像现在一样使用密码授予流程,除非您从后端而不是前端进行调用。

关于azure - Microsoft 从 oauth2 登录问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41985822/

相关文章:

azure - 引用 'Microsoft.Resources/deployments/' 需要 API 版本

javascript - 如何获取日期数组之间的 StartDate 和 EndData

javascript - 我需要帮助来自动显示 react 类中的方法

mysql - mqtt 代理 1.4.1 带有 auth 插件,后端 mysql,无法 sub/pub,用户名或密码错误

java - 在 Android 中检查密码

PHP PDO 登录脚本不起作用。包含错误

azure - 在 Azure : Cores quota have ran out in this region, 上创建 DevOps 项目时出错,请选择其他区域或 VM

azure - 将 AAD 管理角色分配给 AAD 组

azure - 如何将脚本事件输出以 csv/结构化格式推送为接收器

reactjs - 为什么函数从不调用 redux thunk