首页 > 解决方案 > 如何使用 Reactjs 使用 oauth2 Password Grant 对用户登录进行身份验证?

问题描述

我和我的朋友正在使用 Spring-Boot Java 作为后端和 Reactjs 作为前端来构建这个反馈 Web 应用程序。我们最近弄清楚了 Oauth2 是如何工作的,以及在哪里可以使用 Postman 对其进行设置和测试。

现在我们被困在尝试在 Reactjs 中进行 POST 获取,其中包括 ClientID、Secret、用户名、密码并返回 Token。我们能够执行常规 POST 请求并在我们的服务器上保存用户,但授权发布需要更多参数这一事实对我们来说很复杂。

这是我到目前为止所尝试的:

export function PostData(type, userData)  { //disregard parameters for now
  let BaseURL = "http://localhost:8080/";

  return new Promise((resolve, reject) => {
    fetch(
      "http://localhost:8080/oauth/token?grant_type=password&username=user&password=user123",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          clientId: "my-trusted-client",
          clientSecret: "secret",
          scope: "user_info"
        })
      }
    )
      .then(response => response.json())
      .then(res => {
        resolve(res);
        console.log(res);
      })
      .catch(error => {
        reject(error);
      });
  });
}

我所做的只是对我们的 Rest API 的“静态”请求。我正在尝试在 Reactjs 中重新创建我在 Postman 中所做的事情:

有没有人可以帮我重写上面的代码,以便我可以对尝试登录的用户进行身份验证?另外,关于收到令牌后如何继续前进的任何建议?

我们是试图更多地了解我们的 CS 热情的学生,我们非常感谢任何建议。

先感谢您,

标签: javascriptjavareactjsspring-bootoauth-2.0

解决方案


OAuth2 请求需要一个 Content-Type: application/x-www-form-encoded 的请求,这意味着您需要发送一个 x-www-form-encoded 正文,而不是 json(例如 grant_type=password&username=...)

fetch(
  "http://localhost:8080/oauth/token",
  {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-encoded"
    },
    body: “grant_type=password&clientId=my-trusted-client&username=user&password=user123&scope=user_info“
  }
)

另请注意,在从不受信任的客户端(即任何未在您的服务器上运行的任何东西)发送请求时,您不应包含客户端密码。这不是必需的,并且可能会将秘密暴露给攻击者。


推荐阅读