Couchdb Vue.js authentication - authentication

I'm trying to move a node/express authentication application over to vue.js. I am able to successfully authenticate getting a 200 code. However, the response returned from couchdb does not contain the "set-cookie" header, which contains the much needed AuthSession token. The code that I am using in my Vue component is:
var reqBody = "name="+user+"&password="+pass;
var reqBodyLength = reqBody.length;
console.log(reqBodyLength);
this.$http.post('http://localhost:5984/_session/', reqBody, {headers: {'Content-Type' : 'application/x-www-form-urlencoded', 'Accept' : 'application/json'}}).then(response => {
console.log("response: " + JSON.stringify(response));
console.log("response.headers: " + JSON.stringify(response.headers));
console.log("response.headers.set-cookie: " + JSON.stringify(response.headers["set-cookie"]));
}, response => {
alert('you unauthorized, fool!')
})
Has anyone ever had an issue getting the "set-cookie" header?
Thanks, Tyler

Couch's AuthSession is HttpOnly cookie and therefore can't be accessed through a client side script. But the cookie itself should be set to a browser by that _session query, so all the consequent requests will be authorized.
BTW, /_session also accepts JSON payload, at least in CouchDB 1.6, so the query doesn't have to be in x-www-form-urlencoded form.

Related

React Native - Axios - Google Identity Refresh Token 401 error

I'm using custom tokens and firebase auth. I'm successfully logging in users with email & password and storing the accessToken and refresh tokens. When I go to use the refresh token to get a new access token I'm getting a 401 error. When I try the same post link I'm using in a chrome extension based plugin (for testing REST API's) - the request is successful and I get the desired response. Though with my code in expo & react native I get just a plain, unhelpful 401 error.
My code is as follows:
const headers = {
'Authorization': `Bearer ${accessToken}`
}
const data ={
grant_type : "refresh_token",
refresh_token : refreshToken
}
await axios.post(urlTest, data, {
headers: headers
})
.then((response) => {
console.log("Success! ", response)
})
.catch((error : Error) => {
console.error(error.name, error.message);
})
Not sure what I'm doing wrong here. Maybe a cors issue? A fresh pair of eyes would be welcome.
Thanks!
Seems it might have been a CORS issue. Changed where I was hosting the code to handle posting and getting new access token. Works a treat now.

Can't set authorization and token in headers with axios in VueJS

I'm trying to set a JWT token authentication on a VueJS client and PHP API (using Zend and firebase).
I manage to log an user in with the creation of a JWT token stored in LocalStorage. Now I would like to send back this token to the API (so as to the API decode the JWT and return associated infos). I try to set the "Authorisation: Bearer + token" in the header from VueJS using axios but I always have a problem.
Here is a code snippet :
function getInfos() {
return axios({
method: 'get',
url: MYURL,
headers: {
Authorization: 'Bearer ' + localStorage.getItem('user')
}
})
.catch(handleResponse)
}
First I got this error :
Access to XMLHttpRequest at 'MYURL' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Then I don't have any Authorization in header when I want it in my PHP API :
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: *');
$request = new Request();
I know that I probably have to use
axios.defaults.headers.post or maybe axios.interceptors but I'm a beginner so I have no idea how to use it properly..
I hope someone will be able to help me ! Thank you
I think * doesn't work when setting custom headers you have to Type in header('Access-Control-Allow-Headers: Authorization') atleast that's an issue i had

React native fetching data from secured API's endpoint with JWT

I'm developing React Native application which is connected to Web API written in ASP.NET Core 2.1. I'm trying to make GET request to my secured API's endpoint, but it doesn't work both with fetch and axios.
Noteworthy is fact, when I make request to unsecured (marked as AllowAnonymous) endpoint, everything works fine.
I'm passing following header 'Authorization' : 'Bearer ' + MY_TOKEN
When I tried to use axios, then it returned HTTP 401. When using fetch it returns HTTP 500.
const url = `${baseUrl}/api/cars/get`
fetch(url, {
headers: new Headers({
Authorization: "Bearer <MY_TOKEN_HERE>"
}), method: "GET"
})
I'm sure the token is valid because I am able to get data from API with Postman and with .NET Core console application client.
Is there any way to get the data from secured API's endpoint?
I solved the issue with just one line of code.
axios.defaults.headers.common['Authorization'] = `Bearer ${TOKEN}`
Then I am able to invoke the get request.
const url = `${baseUrl}/api/values`;
axios.get(url)
.then(data => {
console.log(data);
})
.catch(error => {
})
Hope it helps someone who will have such issue in the future.

Angular-5 StripeConnect -303 Error -Response for Preflight is invalid (Redirect)

I am doing StripeConnect(Standard Account Type) with Angular 5 and Asp.NetCore.
I am able to get redirected to required URL with code={} value.
When I am trying to use this code in below URL,
https://connect.stripe.com/oauth/token\client_secret={{secret test key}}\code={{code}}\grant_type = authorization_code"
1.I get preflight is invalid (Redirect) error in browser from my angular solution.
2.The html for stripe login page from Postman.
The code I wrote for making the post call to above URL (in angular) is :
getCredentialsFromStripe(code: any)
{
let Url = "https://connect.stripe.com/oauth/token";
//\client_secret=" + {{key}} + "\code=" + code + "\grant_type
= authorization_code";
return this.http.post(Url, {
Body: "client_secret = {{key}}\code =" + code,
Headers: {
'Authorization': 'Bearer '+ code,
"Accept": "application/json; charset=UTF-8",
"Access-Control-Allow-Origin": "https://connect.stripe.com/oauth/token"
}
}).map(res => res.json());
}
As per suggestions on internet,I tried making the post call from backend(.NET core(2.0) API for me),but didn't get through in creating account for standard account type.
Moreover testing from postman is giving the full html page of login ,instead of getting this object:
{
"token_type": "bearer",
"stripe_publishable_key": "{PUBLISHABLE_KEY}",
"scope": "read_write",
"livemode": false,
"stripe_user_id": "{ACCOUNT_ID}",
"refresh_token": "{REFRESH_TOKEN}",
"access_token": "{ACCESS_TOKEN}"
}
Can anybody give me a lead on this.I have been stuck past two days.
Any thoughts will be really appreciated.
Well,I was able to fix it. Instead of creating accounts using the URL (given above) in angular project (following the node.js documents),I called the stripe api's in Asp.net core (my api solution) and called them.It worked easily.

Sending axios get request with authorization header

I have tried to send axios get request using vue.js and it worked just fine when there was no need to send headers. However, when it was required to send an authorization jwt, i was getting CORS error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." I don't know why is this problem occurring since there is Access-Control-Allow-Origin: '*' header in the response. My code is the following:
axios.get(url, {
headers: {
'Authorization': 'Bearer TOKEN'
}
})
.then(function (response) {
console.log(response.data)
})
The weirdest thing is when I use querystring.stringify or JSON.stringify on the header, I don't get the error 403(forbidden), but just an error 401 - Unauthorized. I tried with variable and with the token itself and it didn't work.
I tried to send a post request in order to get a web token with required data - username an password and it worked. I was able to get the token.
I made a whole bunch of research the last two days on this and I found different kind of request structure and configs which I tried all of them, but none were efficient. Is there a way to check if the request is being send with the header? Is something else the problem? If someone can help, I would appreciate. Thanks.
I think you should add this code to the bootstrap.js (or where the axios is defined):
window.axios = require('axios'); // I think its already added
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest'
};
You didn't mention, but I guess you use laravel, or other framework, what is protected from csrf attack, thats why you need to add the generated token to your ajax request header.