How To Send Basic Auth With Axios: 3 Years, 6 Months Ago 2 Months Ago 187k Times

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

request - How to send Basic Auth with axios - Stack Overflow 12/9/20, 10:48 AM

How to send Basic Auth with axios


Asked 3 years, 6 months ago Active 2 months ago Viewed 187k times

I'm trying to implement the following code, but something is not working. Here is the code:

119 var session_url = 'http://api_address/api/session_endpoint';


var username = 'user';
var password = 'password';
var credentials = btoa(username + ':' + password);
var basicAuth = 'Basic ' + credentials;
axios.post(session_url, {
20 headers: { 'Authorization': + basicAuth }
}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});

It's returning a 401 error. When I do it with Postman there is an option to set Basic Auth; if I
don't fill those fields it also returns 401, but if I do, the request is successful.

Any ideas what I'm doing wrong?

Here is part of the docs of the API of how to implement this:

This service uses Basic Authentication information in the header to establish a user
session. Credentials are validated against the Server. Using this web-service will
create a session with the user credentials passed and return a JSESSIONID. This
JSESSIONID can be used in the subsequent requests to make web-service calls.*

request postman axios

edited Apr 24 '18 at 4:24 asked May 19 '17 at 14:33


pillravi Emmanuel
3,377 4 14 30 1,527 2 9 15

6 using
By Answers Active
our site, you acknowledge that you have read and understand our Cookie Policy, Privacy PolicyOldest
, and Votes

our Terms of Service.

There is an "auth" parameter for Basic Auth:


https://stackoverflow.com/questions/44072750/how-to-send-basic-auth-with-axios Page 1 of 9
request - How to send Basic Auth with axios - Stack Overflow 12/9/20, 10:48 AM

There is an "auth" parameter for Basic Auth:

177 auth: {
username: 'janedoe',
password: 's00pers3cret'
}

Source/Docs: https://github.com/mzabriskie/axios

Example:

await axios.post(session_url, {}, {


auth: {
username: uname,
password: pass
}
});

edited Feb 6 at 7:32 answered May 29 '17 at 9:54


luschn
66.9k 6 101 114

4 hello, how can I set that into all the axios call? I need to add Basic auth to all ajax calling.
axios.defaults.auth = { username: 'dd', password: '##'} this is not working for me. – hkg328 Feb 20
'18 at 12:53

maybe this helps: gist.github.com/EQuimper/dc5fe02dcaca4469091729e1313f78d1 – luschn Feb 20


'18 at 15:16

btw, you can als write a wrapper around axios for those kind of things – luschn Feb 20 '18 at 15:17

I made wrapper for that. but that api gives me 401 error – hkg328 Feb 20 '18 at 15:20

1 @hkg328 you need to encode the string username:password to base64 if you want to manually set
the header. something like import btoa from 'btoa-lite'; token = btoa(username + ':' + password); then
set the header to 'Basic ' + token; – shrumm Mar 19 '18 at 17:25

The reason the code in your question does not authenticate is because you are sending the
auth in the data object, not in the config, which will put it in the headers. Per the axios docs,
61 the request method alias for post is:

axios.post(url[, data[, config]])


+50

https://stackoverflow.com/questions/44072750/how-to-send-basic-auth-with-axios Page 2 of 9
request - How to send Basic Auth with axios - Stack Overflow 12/9/20, 10:48 AM

Therefore, for your code to work, you need to send an empty object for data:

var session_url = 'http://api_address/api/session_endpoint';


var username = 'user';
var password = 'password';
var basicAuth = 'Basic ' + btoa(username + ':' + password);
axios.post(session_url, {}, {
headers: { 'Authorization': + basicAuth }
}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});

The same is true for using the auth parameter mentioned by @luschn. The following code is
equivalent, but uses the auth parameter instead (and also passes an empty data object):

var session_url = 'http://api_address/api/session_endpoint';


var uname = 'user';
var pass = 'password';
axios.post(session_url, {}, {
auth: {
username: uname,
password: pass
}
}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});

answered Apr 23 '18 at 19:30


pillravi
3,377 4 14 30

1 THIS HELPED, THANKS – superrcoop Feb 7 '19 at 21:51

1 This should be the accepted answer. The accepted answer is just a duplicate of the documentation.
– Sinister Beard Sep 6 '19 at 14:41

no need for that Nov 2020: github.com/axios/axios#axiosrequestconfigdG9tbzp0b21vOTgy –


cikatomo Nov 5 at 7:35

For some reasons, this simple problem is blocking many developers. I struggled for many
hours with this simple thing. This problem as many dimensions:
6
https://stackoverflow.com/questions/44072750/how-to-send-basic-auth-with-axios Page 3 of 9
request - How to send Basic Auth with axios - Stack Overflow 12/9/20, 10:48 AM

1. CORS (if you are using a frontend and backend on different domains et ports.

2. Backend CORS Configuration

3. Basic Authentication configuration of Axios

CORS

My setup for development is with a vuejs webpack application running on localhost:8081 and a
spring boot application running on localhost:8080. So when trying to call rest API from the
frontend, there's no way that the browser will let me receive a response from the spring
backend without proper CORS settings. CORS can be used to relax the Cross Domain Script
(XSS) protection that modern browsers have. As I understand this, browsers are protecting
your SPA from being an attack by an XSS. Of course, some answers on StackOverflow
suggested to add a chrome plugin to disable XSS protection but this really does work AND if it
was, would only push the inevitable problem for later.

Backend CORS configuration

Here's how you should setup CORS in your spring boot app:

Add a CorsFilter class to add proper headers in the response to a client request. Access-
Control-Allow-Origin and Access-Control-Allow-Headers are the most important thing to have
for basic authentication.

public class CorsFilter implements Filter {

...
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse
servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;

response.setHeader("Access-Control-Allow-Origin", "http://localhost:8081");
response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT,
DELETE, TRACE, OPTIONS, PATCH");
**response.setHeader("Access-Control-Allow-Headers", "authorization,
Content-Type");**
response.setHeader("Access-Control-Max-Age", "3600");

filterChain.doFilter(servletRequest, servletResponse);

}
...
}

https://stackoverflow.com/questions/44072750/how-to-send-basic-auth-with-axios Page 4 of 9
request - How to send Basic Auth with axios - Stack Overflow 12/9/20, 10:48 AM

Add a configuration class which extends Spring WebSecurityConfigurationAdapter. In this


class you will inject your CORS filter:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
@Bean
CorsFilter corsFilter() {
CorsFilter filter = new CorsFilter();
return filter;
}

@Override
protected void configure(HttpSecurity http) throws Exception {

http.addFilterBefore(corsFilter(), SessionManagementFilter.class) //adds


your custom CorsFilter
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/api/login")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.authenticationProvider(getProvider());
}
...
}

You don't have to put anything related to CORS in your controller.

Frontend

Now, in the frontend you need to create your axios query with the Authorization header:

https://stackoverflow.com/questions/44072750/how-to-send-basic-auth-with-axios Page 5 of 9
request - How to send Basic Auth with axios - Stack Overflow 12/9/20, 10:48 AM

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<p>{{ status }}</p>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
status: ''
},
created: function () {
this.getBackendResource();
},
methods: {
getBackendResource: function () {
this.status = 'Loading...';
var vm = this;
var user = "aUserName";
var pass = "aPassword";
var url = 'http://localhost:8080/api/resource';

var authorizationBasic = window.btoa(user + ':' + pass);


var config = {
"headers": {
"Authorization": "Basic " + authorizationBasic
}
};
axios.get(url, config)
.then(function (response) {
vm.status = response.data[0];
})
.catch(function (error) {

Hope this helps.

edited Apr 18 '19 at 1:18 answered Apr 17 '19 at 13:29


Erick Audet
158 2 9

noob CORS question, this is only used in development, right? – Len Joseph Apr 17 '19 at 14:27

No, it is also and mostly in production. – Erick Audet Apr 17 '19 at 14:32

The solution given by luschn and pillravi works fine unless you receive a Strict-Transport-
https://stackoverflow.com/questions/44072750/how-to-send-basic-auth-with-axios Page 6 of 9
request - How to send Basic Auth with axios - Stack Overflow 12/9/20, 10:48 AM

The solution given by luschn and pillravi works fine unless you receive a Strict-Transport-
Security header in the response.
5
Adding withCredentials: true will solve that issue.

axios.post(session_url, {
withCredentials: true,
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
},{
auth: {
username: "USERNAME",
password: "PASSWORD"
}}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});

answered May 31 '19 at 8:38


Leonard Saers
428 8 19

An example (axios_example.js) using Axios in Node.js:

https://stackoverflow.com/questions/44072750/how-to-send-basic-auth-with-axios Page 7 of 9
request - How to send Basic Auth with axios - Stack Overflow 12/9/20, 10:48 AM

const axios = require('axios');


const express = require('express');
const app = express();
const port = process.env.PORT || 5000;

app.get('/search', function(req, res) {


let query = req.query.queryStr;
let url = `https://your.service.org?query=${query}`;

axios({
method:'get',
url,
auth: {
username: 'xxxxxxxxxxxxx',
password: 'xxxxxxxxxxxxx'
}
})
.then(function (response) {
res.send(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
});

var server = app.listen(port);

Be sure in your project directory you do:

npm init
npm install express
npm install axios
node axios_example.js

You can then test the Node.js REST API using your browser at:
http://localhost:5000/search?queryStr=xxxxxxxxx

Ref: https://github.com/axios/axios

answered May 21 '18 at 12:17


Yuci
14.5k 5 74 85

If you are trying to do basic auth, you can try this:

https://stackoverflow.com/questions/44072750/how-to-send-basic-auth-with-axios Page 8 of 9
request - How to send Basic Auth with axios - Stack Overflow 12/9/20, 10:48 AM

const username = ''


const password = ''

const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')

const url = 'https://...'


const data = {
...
}

axios.post(url, data, {
headers: {
'Authorization': `Basic ${token}`
},
})

This worked for me. Hope that helps

answered Sep 14 at 9:07


Fotie M. Constant
31 1 4

https://stackoverflow.com/questions/44072750/how-to-send-basic-auth-with-axios Page 9 of 9

You might also like