我和我的朋友们正在使用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中重新创建我在邮递员中所做的事情:有没有人可以帮助我重写上面的代码,以便我可以对尝试登录的用户进行身份验证?另外,关于收到令牌后如何继续前进的任何建议?我们是学生,他们试图更多地了解我们对CS的热情,任何建议均深表感谢。
1 回答

临摹微笑
TA贡献1982条经验 获得超2个赞
OAuth2请求要求使用内容类型: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“
}
)
另请注意,从不受信任的客户端发送请求时,您不应包含客户端密码(即,服务器上未运行的任何内容)。这是没有必要的,并且可以向攻击者公开此秘密。
添加回答
举报
0/150
提交
取消