Can express-session be used in React Native? - node.js

My React Native app needs to use sessions for when users are signed in, but I'm not sure how to implement it. At first I thought I'd need AsyncStorage to store the session ID and attach it to each request to the server, but now I'm wondering if any additional code is required on the client side.
For example, I believe express-session sets a cookie automatically in the browser which means you just have to send the cookie. Is this the same for React Native/mobile applications? In other words, if I send a response that contains a cookie will that cookie automatically be attached to each future request, or do I need to store it somehow?

Have you tried axios ?, it automatically set the cookie it receive to client when you specify the option withCredentials: true.
example:
axios({
method: 'post',
url: '/api/auth/login',
data: {
username: username,
hashpass: hash(password)
},
withCredentials: true
}).then(res => console.log('login success'))
.catch(res => {
console.log('error')
})

Related

Why am i not getting the cookies at different path

Why am i getting a authorization header when i send the requests to / from the client but when i send requests to /auth/signup on the same origin i'm not getting the authorization headers.
Here is how i'm setting my cookie in the browser so that i will send them as a header from the browser.
export const storeRefreshToken = (res: Response, token: string): void => {
// Invalidate old tokens
res.cookie(__cookieName__, token, {
httpOnly: true, // they can not be accessed using javascript
path: "/",
sameSite: "lax",
});
};
I'm using jwt authentication and graphql, I'm getting the headers when i'm at / but if i change to /auth/signin I'm not getting anything. What may be posibly the problem when setting cookies.

React Native authentication using Express sessions?

I currently have a web application that uses React frontend + Express sessions backend for authentication and authorization. I'm wondering if I can use the same or similar workflow for authenticating mobile users. This is how I authenticate users in my web application:
req.session.user = { id: user.rows[0].id }; // Set session cookie with user's ID
res.status(200).json({status: "success", message: "Login successful"});
It's very simple. If the passed login credentials are correct - I create a session with the user's ID that comes from the database and return a success to the front end.
Can I do something similar when using React Native as front end? I'm new to mobile development, but does the mobile client even have a cookie storage similar to a web browser? Very thankful for any input :)
Yes you can use cookies for authentication, I recommend to use fetch function to do http request. You need to pass access-control-allow-credentials header to share the cookies between server and client.
Example:
var params = {
method: "POST",
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'access-control-allow-credentials': 'true'
}
}
params.body = JSON.stringify(body)
const response = await fetch(url, params)
const json = await response.json()
Call the exact same function from react native as it is from react and persist data using this library react-native-async-storage.

How to implement JSON web token on front end side?

I am working on a nodejs express application. I used Passport's JSON web token for authentication. I have successfully created a JSON web token and it's working fine in Postman and also verifies when token passes into authorization. But I stuck on front-end side.
app.get('/profile',passport.authenticate('jwt',{session:false}),function(req,res){
// res.json({user:user.req});
// console.log(req.query.token);
res.json('bingo u cant see this without token')
});
How do I send the token in the headers like I did in Postman to this (/profile) route, i.e how to implement token on front end side so that it first checks token?
It depends on the kind what you are using to make your request at the frontend
if you are using ajax, do something like this
$.ajax({
type: 'POST',
url: url,
headers: {
"authToken":"your token" //you could save it in localstorage when recieved
}
//OR
//beforeSend: function(xhr) {
// xhr.setRequestHeader("My-First-Header", "first value");
// xhr.setRequestHeader("My-Second-Header", "second value");
//}
})
and if it's axios try doing it like this
post(url, {
headers: { authToken: token }
})

Browser does not set cookie

In my NodeJS Express app (built with feathers); I'm trying to work with cookies with client-side fetch from client javascript. I have Express using the cooke-parser middleware.
I have tried setting the credentials header to same-origin, but that has stopped working (it worked fine yesterday, and a few times today... but I've been trying to build up the cookie to what I need and it just doesn't seem to reliably work).
This is my test express route:
app.post('/setjwt', (req, res, next) => {
res.cookie('acokie', 'lol');
res.status(200);
res.send();
});
I'm using fetch in chrome dev tools console to test sending requests like so:
fetch('/setjwt', { method: 'POST', headers: { credentials: 'same-origin' } } );
These are the headers:
But there is no cookie listed in the Application tab nor available in document.cookie.
The reason I have this route is two fold:
Understand how cookies work and interop with Express.
Get rid of this hacky route altogether and get the headers/environment set up correctly so my feathers authentication service's Set-Cookie response header is respected by the browser.
The feathers client on the login page is set up with fetch as its rest implementation, and I can set
fetch('/setjwt', { method: 'POST', headers: { credentials: 'same-origin' } } ); won't work.
The credentials property cannot be specified like that with fetch. The correct code is:
fetch(
'/setjwt',
{
method: 'POST',
credentials: 'same-origin',
headers: { whatever: 'somevalue' }
});
As for setting it up so that the feathers authentication service would work, again, it's not a normal header so brushing up on the documentation hopefully might yield something useful, but I don't think the feathers-rest wrapper over fetch supports passing non header options.

Session lost after redirect

I use fetch() to send a post request for logon,
after server validation, I use req.session.account = account[0]; to save the account information to the session and return a redirect URL,
But after the redirect, the account information in the session is lost, why is that?
If you would have some example code, that would help us track down the problem. My first idea would be to make sure express-session is properly configured:
var app = express();
var session = require('express-session');
app.use(session({
secret: 'ibfiyegfiyegfe' // Secret is a required option.
}));
For futher configuration options, see the express-session repository.
EDIT: Based on the additional information, I'm guessing you have express-session configured to also use cookies for managing the sessions. What this means, is that for every HTTP request Express sends a response back that includes a cookie. jQuery based AJAX calls will ignore the response cookie however, which causes consecutive requests to Express to look as if you never logged in. To allow saving the cookie when performing AJAX requests with jQuery, use the xhrFields field to enable withCredentials:
$.ajax({
url: "http://....",
type: "POST",
xhrFields: {
withCredentials: true
},
data: {username: username, password: password},
success: function(responseBody) {
console.log("success!");
},
error: function(responseBody) {
console.log("error!");
}
});
Hope this helps.
Sorry to everyone, I don't making the question clear.
I use the fetch() method send a request to logon.
fetch('/logon', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
account: account,
password: password
})
}).then(function(response){
return response.json();
}).then(function(json){
if(json.success == 1){
window.location.href = json.redirecturl;
}else{
indexDispatcher.dispatch({
actionType: 'logonFaild',
errorInfo: json.msg
});
}
});
And the server's response is just simple JSON:
if (err) {
consoloe.log(err);
} else {
req.session.account = account[0]; //save account to session
var redirecturl = '/team/' + team[0].id;
console.log("account添加到session了");
res.json({
success: 1,
redirecturl: redirecturl
});
}
But when the client get the redirecturl and redirect, the account data is lost,so it will occur a TypeError: Cannot read property 'id' of undefined(id is saved in req.session.account).
But when I use jquery $.ajax relpace fetch, it works well. I don't know the reason.
I had the same experience like you hundreds of times which I finally found the problem. You don't need to worry if cookies enable or disable.
You just have to re-declare parts of your scripts (variables-the data which you want to display) in a if else condition.
Just redeclare the same thing using !isset and then else with the same variables mentioned twice in the if else condition, if you understand what i mean.
It will call back the same variables over and over. And make sure start session is above the page. no need to worry about headers or white lines, it has actually nothing to do with it.
I've tried it a million times. You don't need to bother using ajax etc. PHP can do almost everything. cheerio.

Resources