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.
Related
Getting 500 internal server error for my next authentication.
I implemented everything according to the docs from Next Auth.
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import axios from "axios";
import { API_URL } from "./../../../helpers/api/mutations";
const options = {
providers: [
CredentialsProvider({
name: "Credentials",
API works fine in a separate react component but fails only on Next Auth.
async authorize(credentials) {
const user = axios({
url: API_URL,
method: "post",
data: {
query: `mutation($mobileNumber:String,$mobileCountryCode:String,$otp:Int){
verifyPhoneOTP(
mobileNumber: $mobileNumber,
mobileCountryCode: $mobileCountryCode,
otp:$otp
)
{accessToken
expiresAt}
}`,
variables: {
mobileNumber: credentials.mobile,
mobileCountryCode: credentials.email,
otp: credentials.otpFormatt,
},
},
validateStatus: (status) => {
if (status == 500) {
console.log(status, "status axios log");
console.log(credentials, "credentials log");
return true;
}
},
headers: {
"User-Agent":
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
Accept: "application/json; charset=UTF-8",
},
})
.catch((error) => {
console.log(error.response.data, "axios fail calls");
})
.then((result) => {
Currently I can see this console log "axios calls" successfully displays itself on the terminal but the tokens and sessions aren't returned.
console.log(result.data, "axios calls");
console.log(credentials, "creds");
return result.data.data
});
if (user) {
return user;
} else {
return null;
}
},
}),
],
};
const callbacks = {
async jwt(token, user) {
if (user) {
token.accessToken = user.token;
}
return token;
},
secret:process.env.SECRET,
async session(session, token) {
session.accessToken = token.accessToken;
return session;
},
};
export default (req, res) => NextAuth(req, res, options);
Error 500 means server error. Check you api server whether it is running or stopped. Error 500 here has nothing to do with nextjs, it is all about the back-end server.
I am using NuxtJs auth module to handle my authorization in the state. For the auth I wrote an express api which works.
I have following configuration in my nuxt.config.js:
axios: {
baseURL: 'http://localhost:4000/api'
},
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/users/login', method: 'post', propertyName: 'data.token' },
user: { url: '/users/me', method: 'get', propertyName: 'data' },
},
}
}
},
And in my login component I call the login route like this:
const { data } = await this.$auth.loginWith('local', {
data: this.login
})
This call the /api/users/login route successfully (200) and after that calls the /api/users/me with an error saying
xhr.js:178 GET http://localhost:4000/api/users/me 401 (Unauthorized)
In postman I am calling the api route which returns the user like this*
> Get - localhost:4000/api/users/me
>
> Authorization:
>
> Type: Bearer Token Token: xxxx
Which returns the users data.
I read that nuxt auth module default the type to 'Bearer' but in my case it does not work.
The user login work but the second route which returns the user data does not work due to authorization. The Api is not inside the nuxtjs it is a different project written in Express.
You can try this:
axios: {
baseURL: 'http://localhost:4000/api' },
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/users/login', method: 'post', propertyName: 'data.token' },
user: { url: '/users/me', method: 'get', propertyName: 'data' },
},
tokenType: ''
}
}
},
Setting tokenType to an empty string overrides the default "Bearer". Some server configurations may throw a 401.
I wanted to make a request to ADP with autho1.0a
I was able to make successful requests as I wanted in postman but not through my application.
postman screenshot
npm module used
similar post
Code I tried
Part:1 Signature generation
const crypto = require('crypto')
const OAuth = require('oauth-1.0a')
const oauthObj = {};
function hash_function_sha1(base_string, key) {
return crypto
.createHmac('sha1', key)
.update(base_string)
.digest('base64')
}
oauthObj.getSignature = async payload => {
const { consumerKey,consumerSecret,apiUrl,method} = payload;
const oauth = OAuth({
consumer: { key: `${consumerKey}`, secret: `${consumerSecret}` },
signature_method: 'HMAC-SHA1',
hash_function: hash_function_sha1,
});
const request_data = {
url: `${apiUrl}`,
method: `${method}`
}
const token = {}
// return oauth.toHeader(oauth.authorize(request_data, token));
console.log('header string-----',oauth.toHeader(oauth.authorize(request_data, token)));
return oauth.authorize(request_data, token);
}
module.exports = oauthObj;
Part 2 : Axios Call
let oauthData=`oauth_consumer_key=${consumerKey}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=${oauthTimestamp}&oauth_nonce=${oauthNonce}&oauth_version=1.0&oauth_signature=${oauthSignature}= HTTP/1.1`;
const eventData = await axios({
url:`${apiUrl}?${oauthData}`,
// url:`${apiUrl}?${oauthHeader.Authorization}`,
method:'GET',
headers:{
// ...oauthHeader,
'Authorization':'OAuth',
'Accept': 'application/json',
// "Authorization": `'OAuth oauth_consumer_key="${consumerKey}", oauth_nonce="${oauthNonce}", oauth_signature="${oauthSignature}", oauth_signature_method="HMAC-SHA1", oauth_timestamp="${oauthTimestamp}", oauth_version="1.0"`
}
});
Expected Result:
{
"code": "Gone",
"message": "Event with token 954c183f-26e0-4f9e-b452-c089aaf9842f has already been consumed."
}
Receiving error:
response: {
status: 401,
statusText: 'Unauthorized',
headers: {
What might have gone wrong ?
Try using request node package oauth option
request.get(`${apiUrl}?${oauthData}`, {
oauth: {
consumer_key: '..',
consumer_secret: '..',
},
headers: {
Accept: 'application/json'
},
}, function (err, res, body) {
console.log(body);
})
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!
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 });