Basic authentication in axios - javascript

I've got an problem with basic authentication with axios, i know axios have a dedicated option for this. But it doesn't work in my implementation. I've create an Axios instance, with the auth parameters included, but i still get an 401 (Unauthorized). When i remove the password from the server, the api calls are working.
const instance = axios.create({
baseURL: process.env.VUE_APP_API_URL,
withCredentials: true,
auth: {
username: 'username',
password: 'password'
}
});
instance.CancelToken = axios.CancelToken;
instance.isCancel = axios.isCancel;
instance.interceptors.response.use((response) => {
return response;
}, (error) => {
error.response = {
success: false,
message: {
'type': 'error',
'message': i18n.t('sentence.global.error.message')
}
};
return Promise.reject({
...error
});
});
export default instance;
I also tried this:
const instance = axios.create({
baseURL: process.env.VUE_APP_API_URL,
withCredentials: true,
},{
auth: {
username: 'username',
password: 'password'
});
}
....
export default instance;
I also tried prefixing the apiurl with username:password#apiurl.com
Thanks in advance!

Related

Axios + reactJS+ passportJS login redirect not working?

I'm trying to implement user authentication for the first time, I can't get the redirect to work after a successful login.
Function in react:
const login = () => {
Axios({
method: "POST",
data: {
email: loginEmail,
username: loginEmail,
password: loginPassword,
},
withCredentials: true,
url: "http://localhost:5000/login",
}).then((res) => console.log(res));
};
Backend user controller:
exports.login = (req, res) => {
const { email, name, username, password } = req.body;
const user = new User({ email, name, username });
req.login(user, (err) => {
if (err) return next(e);
console.log("LOGGED IN")
res.redirect('/');
});
};
The console messages do print when I enter a valid user/password, but I just can't get the page to redirect after a successful log in. I've tried using history.push instead of redirecting from the backend, but it would push regardless of whether or not the log in is successful.
const login = () => {
Axios({
method: "POST",
data: {
email: loginEmail,
username: loginEmail,
password: loginPassword,
},
withCredentials: true,
url: "http://localhost:5000/login",
}).then(history.push("/"));
};
Does anyone have any insight of why I am unable to redirect from the backend? How can I better approach this?
In backend user controller instead of res.redirect send res.send(// if authentication is completed send true, else send false).
Now you can access this message in then function.
const login = () => {
Axios({
method: "POST",
data: {
email: loginEmail,
username: loginEmail,
password: loginPassword,
},
withCredentials: true,
url: "http://localhost:5000/login",
}).then((res) => {(res.data===true) && (history.push("/"))});
};
Try this..
const login = async () => {
const res = await Axios({
method: "POST",
data: {
email: loginEmail,
username: loginEmail,
password: loginPassword,
},
withCredentials: true,
url: "http://localhost:5000/login",
});
// if success
history.push("/");
};

Request for an API with Axios - Unauthorized

I'm trying to make the request for an API, using Axios:
const axios = require ("axios")
const httpsAgent = require('https-agent')
const https = require('https')
const instance = axios ({
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
auth: {
username: 'username'
}
})
axios.post("url_api").then(function(response){
console.log(response.data)
}).then(function(response){
console.log(response.data)
}).catch((e)=>{console.log(e)})
but it displays error 401:
TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string
response: {
status: 401,
statusText: 'Unauthorized',
...
},
data: 'Unauthorized'
},
isAxiosError: true,
toJSON: [Function: toJSON]
}
Is there any more configuration to do? Insomnia/Postman works
The code you've here
const instance = axios ({
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
auth: {
username: 'username'
}
})
It's already equivalent to initiating a request, but the problem is you've not passed the url and method parameter which is mandatory
So modify it to
const request = axios ({
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
method: 'post',
url: 'your_api_url_here', // important change
auth: {
username: 'username'
}
})
Or you can simple follow and do
axios.post('url_here', data );
Finally, your code must look like this
const instance = axios({
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
auth: {
username: 'username'
},
method: 'post',
url: 'your_api_url_here',
})
.then(response => console.log(response.data))
.catch((e) => console.log(e));
Choose either one of them but not both.
axios.post("url_api",body,header)

Vue-Auth issue in setting token to header['authorization']

I am having an issue in setting the authorization token to the request header. I always get a 401 Unathuroized issue after setting my header using a bearer driver. Below is my code:
bearer.js
module.exports = {
request: function (req, token) {
this.options.http._setHeaders.call(this, req, {Authorization: 'Bearer ' + token})
},
response: function (res) {
if (res.data.token) {
return res.data.token
}
}
}
main.js
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
import VueAuth from '#websanova/vue-auth'
Vue.use(VueAuth, {
auth: require('#websanova/vue-auth/drivers/auth/bearer.js'),
http: require('#websanova/vue-auth/drivers/http/axios.1.x.js'),
router: require('#websanova/vue-auth/drivers/router/vue-router.2.x.js'),
refreshData: {url: 'auth/refresh', method: 'GET', enabled: false, interval: 30},
fetchData: {url: 'auth/user', method: 'GET', enabled: false},
notFoundRedirect: {path: '/admin'},
rolesVar: 'roles',
})
and the code in login.vue
this.$auth.login({
data: credentials,
url: process.env.VUE_APP_URL + '/api/v1/login',
fetchUser: false,
success: function (response) {
if(response.data){
localStorage.setItem('user',(JSON.stringify(response.data.data)));
this.$auth.user(response.data.data);
this.$auth.watch.authenticated = true;
this.$auth.watch.loaded = true;
this.$router.push('/dashboard');
axios.defaults.headers.common["Authorization"] = "Bearer " + response.data.data.token;
debugger;
}
},
error: function () {
this.$notify({
type: 'warn',
title: 'Login',
text: 'Login failed'
});
},
})
I tried to add a debugger inside the request method of a bearer.js driver, that doesn't seem to execute.

Node request how to handle sessions

I'm using node.JS with request module.
My problem is, I need to authenticate the user on every request because the session is destroyed outside of the .then((response) => {}) block.
How is it possible to save the created session in a class for later use?
I tried out everything without success.
Here is a not working code snippet
login() {
const getLoginUrl = 'https://www.demourl.com/'
const postLoginUrl = 'https://www.demourl.com/account/login/'
rp({
url: getLoginUrl,
jar: this.cookieJar,
method: 'GET'
})
.then((body) => {
var csrftoken = this.cookieJar.getCookies(getLoginUrl)[1].toString().split('=')[1].split(';')[0];
var args = {
url: postLoginUrl,
json: true,
method: 'POST',
data: {
username: this.username,
password: this.password
},
headers: {
'method': 'POST',
'path': '/account/login/',
'cookie': 'csrftoken=' + csrftoken,
},
jar: this.cookieJar,
resolveWithFullResponse: true
}
rp(args)
.then((response) => {
//Here is a valid session
//But how can I use this session in different functions?
console.log('Post demourl.com/account/login success');
})
.catch((error) => {
console.log('Post demourl.com/account/login error: ', error);
});
})
.catch((error) => {
console.log('Get demourl.com error: ', error);
});
}
you should use this function as a middleware and then attach what ever you want to attach in to your req
try in you main script do
'use strict'
const express = require('express');
const login = require('./login');
const app = express()
app.use(login);// use this if you want all your routes to check login or put it in a specific route
app.get('/', (req,res)=>{
//this route is only for loged in users
});
const server = http.createServer(app).listen(process.env.PORT);
module.exports = app;
and in your login script
const login = (req, res, next) => {
const getLoginUrl = 'https://www.demourl.com/'
const postLoginUrl = 'https://www.demourl.com/account/login/'
rp({url: getLoginUrl, jar: this.cookieJar, method: 'GET'})
.then((body) => {
var csrftoken = this.cookieJar.getCookies(getLoginUrl)[1].toString().split('=')[1].split(';')[0];
var args = {
url: postLoginUrl,
json: true,
method: 'POST',
data: {
username: this.username,
password: this.password
},
headers: {
'method': 'POST',
'path': '/account/login/',
'cookie': 'csrftoken=' + csrftoken,
},
jar: this.cookieJar,
resolveWithFullResponse: true
}
rp(args)
.then((response) => {
res.loginResponse = response; // save the response for later use
console.log('Post demourl.com/account/login success');
next();
})
.catch((error) => {
console.log('Post demourl.com/account/login error: ', error);
return res.send(error) //send the error
});
})
.catch((error) => {
console.log('Get demourl.com error: ', error);
return res.send(error) //send the error
});
}
module.exports = login
I never see this.cookieJar being defined. Make sure it's initialized somewhere:
this.cookieJar = request.jar();
If you only use a single cookieJar in your application, you could also use Request's global cookie jar by setting the option jar to true:
// Either by setting it as the default
const request = require('request').defaults({jar: true});
// Or by setting it on each request
request('www.example.com', { jar: true });

Getting access token with axios

I'm working with the Lyft API, and trying to figure out how to get an access token with axios with a node script.
I can manually get an access token by using Postman by filling out the form like this:
When I fill out the form, I can get a new token from Lyft successfully.
I'm trying to translate this into a POST request using axios by doing this:
var axios = require('axios');
var data = {
"grant_type": "client_credentials",
"scope": "public",
"client_id": "XXXXXXXXX",
"client_secret": "XXXXXXXX"
};
var url = "https://api.lyft.com/oauth/token";
return axios.post(url, data)
.then(function(response){
console.log(response.data)
})
.catch(function (error) {
console.log(error);
});
When I run the script, I get this error:
{ error_description: 'Unauthorized', error: 'invalid_client' }
What am I missing from my axios request? Any help would be appreciated!
According to the docs from Lyft (https://developer.lyft.com/docs/authentication), you need to use HTTP Basic auth.
var axios = require("axios");
axios.request({
url: "/oauth/token",
method: "post",
baseURL: "https://api.lyft.com/",
auth: {
username: "vaf7vX0LpsL5",
password: "pVEosNa5TuK2x7UBG_ZlONonDsgJc3L1"
},
data: {
"grant_type": "client_credentials",
"scope": "public"
}
}).then(function(res) {
console.log(res);
});
Happy coding :)
!IMPORTANT THING!
I strongly recommend you to change your secret_id and client_secret asap, because they are not the things to be public, if you use them for an important project or something like that.
I have solved my problem with this code.
var reqData = "grant_type=password&username=test&password=asd";
Axios({
method: 'post',
url: 'http://localhost:60439/token',
data: (reqData),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
}).then((response) =>{
console.log(response)
}).catch((error) =>{
console.log(error);
})
The Best solution was source using the following way. The client sends a POST request with following body parameters to the authorization server
grant_type with the value client_credentials
client_id with the the client’s ID
client_secret with the client’s secret
scope with a space-delimited list of requested scope permissions.
axios.post('https://exmaple.com/oauth/token',
'grant_type=client_credentials&scope=all&client_id=1&client_secret=bb'
)
.then(function(res) {
console.log(res);
})
.catch(error => {
console.log(error)
})
const axios = require("axios");
const qs = require("qs");
const url = "URL";
const data = {
grant_type: "client_credentials",
};
const auth = {
username: "Client ID",
password: "Client Secret",
};
const options = {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
data: qs.stringify(data),
auth: auth,
url,
};
axios(options)
.then((response) => {
console.log(response.data.access_token);
})
.catch((err) => {
console.log(err);
});
The following works. I got it by reading the above comments. The trick was the data field. To be clear use - data: "grant_type=client_credentials"
Example:
const axios = require("axios");
axios.request({
headers:{'Content-Type': 'application/x-www-form-urlencoded'},
url: "/oauth2/token",
method: "post",
baseURL: "https://<ServerFQDN>/",
data: "grant_type=client_credentials",
auth: {
username: "<username>",
password: "<password>"
}
});

Categories

Resources