reactjs - 我们如何在React js中使用axios发送OAuth2.0

标签 reactjs oauth-2.0 axios

我正在解决一个身份验证问题,我必须为我的 React 应用程序实现 OAuth2.0 身份验证。有什么方法可以使用基于 Axios Promise 的库进行身份验证???

最佳答案

您必须在 header 中传递您的 token 。

见下文;

const instance = axios.create({
  baseURL: 'http://localhost/api/',
  headers: {'Authorization': 'basic '+ token}
});

instance.get('/path')
.then(response => {
    return response.data;
})

或者

获得 token 后,在浏览器中设置授权 cookie。 浏览器将始终在向服务器发出的每个请求中发送授权 cookie。您不必通过 Axios get/post 传递它。

更新:

为了从 oAuth 服务器获取访问 token ,请传递 client_id、client_secret、scope 和 grant_type,如下所示;

var axios = require("axios");

axios.request({
  url: "/oauth/token",
  method: "post",
  baseURL: "http://sample.oauth.server.com/",
  auth: {
    username: "myUsername", // This is the client_id
    password: "myPassword" // This is the client_secret
  },
  data: {
    "grant_type": "client_credentials",
    "scope": "public"    
  }
}).then(respose => {
  console.log(respose);  
}); 

我假设您正在使用 grant_type = "client_credentials",如果没有,那么根据您使用的 grant_type,您还必须相应地更改请求参数。

关于reactjs - 我们如何在React js中使用axios发送OAuth2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54487260/

相关文章:

javascript - 为什么即使在 UseEffect Hook 中设置状态后我的 React 状态仍未定义?

javascript - 如果值设置为 this.state.value,React-bootstrap 表单只允许我输入?

javascript - React ref 在 onChange 中没有值

node.js - 如何在 NodeJS 中使用只有 URL 的 Sharp 调整图像大小,使用 async/await,并且没有创建本地副本?

javascript - 当 Promise 被拒绝时如何触发 React 错误边界?

node.js - cURL 的 --form 的 axios 或 ajax 等效项是什么?

javascript - jsx 文件映射错误 : Unable to generate source map (ReactJS)

c# - WebAPI OAuth 注销 - 如何删除 token Cookie?

amazon-web-services - AWS Cognito TOKEN 端点无法将授权代码转换为 token

http - 为什么我的授权 header 不需要 "Bearer"?