Professional Documents
Culture Documents
How To Send Basic Auth With Axios: 3 Years, 6 Months Ago 2 Months Ago 187k Times
How To Send Basic Auth With Axios: 3 Years, 6 Months Ago 2 Months Ago 187k Times
How To Send Basic Auth With Axios: 3 Years, 6 Months Ago 2 Months Ago 187k Times
I'm trying to implement the following code, but something is not working. Here is the code:
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.
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.*
6 using
By Answers Active
our site, you acknowledge that you have read and understand our Cookie Policy, Privacy PolicyOldest
, and Votes
177 auth: {
username: 'janedoe',
password: 's00pers3cret'
}
Source/Docs: https://github.com/mzabriskie/axios
Example:
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
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:
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:
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):
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
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.
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.
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.
...
@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
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
@Bean
CorsFilter corsFilter() {
CorsFilter filter = new CorsFilter();
return filter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
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';
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');
});
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
axios({
method:'get',
url,
auth: {
username: 'xxxxxxxxxxxxx',
password: 'xxxxxxxxxxxxx'
}
})
.then(function (response) {
res.send(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
});
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
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
axios.post(url, data, {
headers: {
'Authorization': `Basic ${token}`
},
})
https://stackoverflow.com/questions/44072750/how-to-send-basic-auth-with-axios Page 9 of 9