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

IT技术 reactjs oauth-2.0 axios
2021-05-03 17:33:15

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

1个回答

您必须在标题中传递您的令牌。

见下文;

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

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

或者

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

更新:

为了从oAuth服务器获取访问令牌,传递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,您还必须相应地更改请求参数。