我正在解决一个身份验证问题,我必须为我的 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/