Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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???

like image 391
Purvish Oza Avatar asked Feb 01 '19 21:02

Purvish Oza


People also ask

What is OAuth JavaScript?

This document explains how to implement OAuth 2.0 authorization to access Google APIs from a JavaScript web application. OAuth 2.0 allows users to share specific data with an application while keeping their usernames, passwords, and other information private.


1 Answers

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.

like image 143
MMH Avatar answered Sep 18 '22 23:09

MMH