How can we send OAuth2.0 with axios in React js

早过忘川 提交于 2020-08-27 06:50:23

问题


I am working on one authentication problem where i have to implement OAuth2.0 authentication for my React App. Is there any way that i can use that authentication with Axios Promise based library???


回答1:


You will have to pass your Token in the header.

See below;

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

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

OR

Set an Authorization cookie in the browser once you get your token. The browser will always send the Authorization cookie in each request made to the server. You won't have to pass it through Axios get/post.

UPDATE:

In order to get the access token from the oAuth server, pass the client_id, client_secret, scope and grant_type as follows;

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);  
}); 

I am assuming that you are using grant_type = "client_credentials", if not, then based on the grant_type you use, you will have to also change the request parameters accordingly.



来源:https://stackoverflow.com/questions/54487260/how-can-we-send-oauth2-0-with-axios-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!