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

2023-11-26

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


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

见下文;

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

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

OR

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

UPDATE:

为了从 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,您还必须相应地更改请求参数。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我们如何在React js中使用axios发送OAuth2.0 的相关文章

随机推荐