How to provide frontend with JSON web token after server authentication? - node.js

So far I have only dealt with server-rendered apps, where after a user logs in via username/password or using an OAuth provider (Facebook etc.), the server just sets a session cookie while redirecting to the relevant page.
However now I'm attempting to build an app using a more 'modern' approach, with React on the frontend and a JSON API backend. Apparently the standard choice for this is to use a JSON web token for authentication, however I'm having trouble working out how I'm meant to provide the JWT to the client so it can be stored in session/local storage or wherever.
Example to illustrate better:
User clicks link (/auth/facebook) to log in via Facebook
User is redirected and shown Facebook login form and/or permission dialog (if necessary)
Facebook redirects user back to /auth/facebook/callback with an authorization code in tow, the server exchanges this for an access token and some information about the user
Server finds or creates the user in the DB using the info, then creates a JWT containing a relevant subset of the user data (e.g. ID)
???
At this point I just want the user to be redirected to the main page for the React app (let's say /app) with the JWT in tow, so the frontend can take over. But I can't think of an (elegant) way to do that without losing the JWT along the way, other than to put it in the query string for the redirect (/app?authtoken=...) - but that will display in the address bar until I remove it manually using replaceState() or whatever, and seems a little weird to me.
Really I'm just wondering how this is typically done, and I'm almost sure I'm missing something here. The server is Node (Koa with Passport), if that helps.
Edit: To be clear, I'm asking what the best way is to provide a token to the client (so it can be saved) after an OAuth redirect flow using Passport.

I recently ran across this same issue, and, not finding a solution here or elsewhere, wrote this blog post with my in-depth thoughts.
TL;DR: I came up with 3 possible approaches to send the JWT to the client after OAuth logins/redirects:
Save the JWT in a cookie, then extract it on the front-end or server in a future step (eg. extract it on the client with JS, or send a request to the server, server uses the cookie to get the JWT, returns the JWT).
Send the JWT back as part of the query string (which you suggest in your question).
Send back a server-rendered HTML page with a <script> tag that:
Automatically saves the embedded JWT to localStorage
Automatically redirects the client to whatever page you like after that.
(Since logging in with JWTs is essentially equivalent to "saving the JWT to localStorage, my favorite option was #3, but it's possible there are downsides I haven't considered. I'm interested in hearing what others think here.)
Hope that helps!

Client: Open a popup window via $auth.authenticate('provider name').
Client: Sign in with that provider, if necessary, then authorize the application.
Client: After successful authorization, the popup is redirected back to your app, e.g. http://localhost:3000, with the code (authorization code) query string parameter.
Client: The code parameter is sent back to the parent window that opened the popup.
Client: Parent window closes the popup and sends a POST request to /auth/provider withcode parameter.
Server: Authorization code is exchanged for access token.
Server: User information is retrived using the access token from Step 6.
Server: Look up the user by their unique Provider ID. If user already exists, grab the existing user, otherwise create a new user account.
Server: In both cases of Step 8, create a JSON Web Token and send it back to the client.
Client: Parse the token and save it to Local Storage for subsequent use after page reload.
Log out
Client: Remove token from Local Storage

here is a login request from the server side. it's storing the token in the header:
router.post('/api/users/login', function (req, res) {
var body = _.pick(req.body, 'username', 'password');
var userInfo;
models.User.authenticate(body).then(function (user) {
var token = user.generateToken('authentication');
userInfo = user;
return models.Token.create({
token: token
});
}).then(function (tokenInstance) {
res.header('Auth', tokenInstance.get('token')).json(userInfo.toPublicJSON());
}).catch(function () {
res.status(401).send();
});
});
here is the login request on the react side, where I am grabbing the token from the header and setting the token in local storage once the username and password pass authentication:
handleNewData (creds) {
const { authenticated } = this.state;
const loginUser = {
username: creds.username,
password: creds.password
}
fetch('/api/users/login', {
method: 'post',
body: JSON.stringify(loginUser),
headers: {
'Authorization': 'Basic'+btoa('username:password'),
'content-type': 'application/json',
'accept': 'application/json'
},
credentials: 'include'
}).then((response) => {
if (response.statusText === "OK"){
localStorage.setItem('token', response.headers.get('Auth'));
browserHistory.push('route');
response.json();
} else {
alert ('Incorrect Login Credentials');
}
})
}

When you get a token from any passport authentication sites you have to save the token in your browser's localStorage. The Dispatch is Redux's Middleware. Ignore dispatch if you don't use redux in your app. you can just use setState here (A bit weird without redux).
Client-side:
Here's something similar API of mine, which returns token.
saving tokens
axios.post(`${ROOT_URL}/api/signin`, { email, password })
.then(response => {
dispatch({ type: AUTH_USER }); //setting state (Redux's Style)
localStorage.setItem('token', response.data.token); //saving token
browserHistory.push('/home'); //pushes back the user after storing token
})
.catch(error => {
var ERROR_DATA;
try{
ERROR_DATA = JSON.parse(error.response.request.response).error;
}
catch(error) {
ERROR_DATA = 'SOMETHING WENT WRONG';
}
dispatch(authError(ERROR_DATA)); //throw error (Redux's Style)
});
So When you make some authenticated requests,you have to attach the token with the request in this form.
authenticated requests
axios.get(`${ROOT_URL}/api/blog/${blogId}`, {
headers: { authorization: localStorage.getItem('token') }
//take the token from localStorage and put it on headers ('authorization is my own header')
})
.then(response => {
dispatch({
type: FETCH_BLOG,
payload: response.data
});
})
.catch(error => {
console.log(error);
});
Here's my index.js:
The token is checked each and everytime, so even if the browser got refreshed, you can still set the state.
checks if the user is authenticated
const token = localStorage.getItem('token');
if (token) {
store.dispatch({ type: AUTH_USER })
}
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
..
..
..
<Route path="/blog/:blogid" component={RequireAuth(Blog)} />
//ignore this requireAuth - that's another component, checks if a user is authenticated. if not pushes to the index route
</Route>
</Router>
</Provider>
, document.querySelector('.container'));
All that dispach actions does is it sets the state.
my reducer file(Redux only) else you can just use setState() in your index route file to provide the state to the whole application. Every time the dispatch is called, it runs a similar reducer file like this which sets the state.
setting the state
import { AUTH_USER, UNAUTH_USER, AUTH_ERROR } from '../actions/types';
export default function(state = {}, action) {
switch(action.type) {
case AUTH_USER:
return { ...state, error: '', authenticated: true };
case UNAUTH_USER:
return { ...state, error: '', authenticated: false };
case AUTH_ERROR:
return { ...state, error: action.payload };
}
return state;
} //you can skip this and use setState() in your index route instead
Delete the token from your localStorage to logout.
caution: Use any different name rather than token to save the token in your browser's localStorage
Server-Side:
considering your passport services file. You must set the header search.
Here's passport.js
const passport = require('passport');
const ExtractJwt = require('passport-jwt').ExtractJwt;
const JwtStrategy = require('passport-jwt').Strategy;
..
..
..
..
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromHeader('authorization'), //client's side must specify this header
secretOrKey: config.secret
};
const JWTVerify = new JwtStrategy(jwtOptions, (payload, done) => {
User.findById(payload._id, (err, user) => {
if (err) { done(err, null); }
if (user) {
done(null, user);
} else {
done(null, false);
}
});
});
passport.use(JWTVerify);
In my router.js
const passportService = require('./services/passport');
const requireAuthentication = passport.authenticate('jwt', { session: false });
..
..
..
//for example the api router the above react action used
app.get('/api/blog/:blogId', requireAuthentication, BlogController.getBlog);

Related

using refresh token to get new access token react and node js

I've built a JWT API for user authentication. I want to use it with react.
my app has these routes:
Node js API Routes:
http://localhost:8080/api/auth/signin -> this route accepts username and password from react and sends back an access token to react which it will save it inside localstorage(I'm planning to use memory instead) and cookie containing refresh token with httpOnly enabled.
http://localhost:8080/api/auth/signup -> this route will add a new user to database based on user input(doesn't relate to authentication process)
http://localhost:8080/api/auth/refreshtoken -> this route will return a new access token based on the sent refresh token from client which was saved inside cookies. and then client will replace it with the expired access token.
http://localhost:8080/api/test/user -> this will check if user is signed in with the access token from client and will send the user data back
React Client Routes:
http://localhost:3000/login -> a route for sending user information for logging in
http://localhost:3000/register -> a route for creating a new user
http://localhost:3000/user -> a protected route which needs user to be logged in to view data.
when I log in to my website I can see the data inside the user route for 20 seconds before the access token expiry. when the access token is expired and I do a new request the server will response with 401 unauthorized code. so this way I can make sure that the access token is expired and I need to use refresh token. I've done that like this:
const API_URL = "http://localhost:8080/api/test/";
const getUserBoard = () => {
return axios.get(API_URL + "user", { headers: authHeader() })
.catch((error) => {
if(error.response.status === 401) {
// if error response status was 401 then request a new token
authService.refreshToken();
window.location.reload();
}else if(error.response.status === 403) {
authService.logout();
window.location.href = "/login";
}
});
};
code to get new access token with refresh token:
const refreshToken = () => {
axios({
url: API_URL + "refreshtoken",
method: "POST",
withCredentials: true
})
.then((response) => {
if(response.data.accessToken) {
const user = JSON.parse(localStorage.getItem("user"));
user.accessToken = response.data.accessToken;
localStorage.setItem("user", JSON.stringify(user));
}
})
.catch((error) => {
console.log("server: " + JSON.stringify(error.response));
})
}
code to set header for receiving data from server using access token:
export default function authHeader() {
const user = JSON.parse(localStorage.getItem('user'));
if (user && user.accessToken) {
// for Node.js Express back-end
return { 'x-access-token': user.accessToken };
} else {
return {};
}
}
the first part for getting new access token on 401 error works good but my refresh token also expires after 40 second. if I send the expired refresh token it won't return a new access token. and because of that again I will receive a 401 error which again will cause a 403 error and here I'll get stuck in an infinite reload loop.
any idea? how can I control tokens expiry?
You're issuing tokens in your node.js app, right? So that is where you should adjust the expiration time of the token. The code which issue tokens should have an option to set the expiration time.
Remember that once the refresh token is expired you should log in again. You can implement something which is called a rolling refresh token. So whenever you call the /api/auth/refreshtoken endpoint you can also issue a new refresh token, with a new expiration time and return it in a cookie.

How to Authenticate the logged in user from a MERN application inside React-Redux And Check with every request?

I am working on my second React/Redux application (I'm new to Redux) and also the first MERN stack app altogether.
Currently, I am having an Authentication problem on the Front-End side in React/Redux Which goes like this:
I have established a protect middleware in my Back-End to check if the user which logged in is always logged in with valid JWT-Token or not by setting the Token inside the Browser Cookie with HttpOnly flag enabled {no secure flag yet but I will enable that too in production step}
The main problem is that once I log in the application, everything is fine and if the user is validated without any errors then inside the authReducer, the isAuthenticated property will be set to true and then logged in user's data is passed to the redux store to be used. but once I redirect to the main feed page of the app everything is gone the isAuthenticated is now false and user data is null so the app crashes.
I know that I must call the auth protected route every time I send a request to the server but I am stuck because it needs some piece of the logged-in user like username or ID to be sent along with the each request to validate it and I can't store them in local storage because of safety issues. { storing sensitive data in local storage is not a good practice}
this is log in function in Redux Actions:
export const loginUser = (loginData) => async (dispatch) => {
try{
setLoading();
const res = await axios({
method: "post",
url: "/users/login",
data: {loginData}
});
dispatch({
type: TYPES.LOGIN_SUCCESS,
payload: {
status: res.data.status,
token: res.data.token,
user: res.data.data.user
}
});
// This below code will set the logged in user after successful login
getLoggedInUser(res.data.data.user.username);
}catch(error){
dispatch({
type: TYPES.LOGIN_FAIL,
payload: {
status: error.response.data.status,
message: error.response.data.message
}
});
}
};
as you see after the successful log in, the token and user data is dispatched to store but after component reload they are gone so I can't re-Authenticate the logged in user.
this is my getLoggedInUser redux action function:
export const getLoggedInUser = (userName) => async (dispatch) => {
try{
setLoading();
const res = await axios.get(`/auth/${userName}`, {
// headers:{
// Cookies: `jwt=${token}`
// }
});
dispatch({
type: TYPES.GET_LOGGED_IN_USER,
payload: res.data.data.loggedInUser
});
}catch(error){
dispatch({
type: TYPES.AUTH_ERROR,
payload: {
status: error.response.data.status,
message: error.response.data.message
}
});
}
};
Any solutions?

Maintaining express sessions when moving between static and dynamic pages on client side

I am trying to set up express sessions for user authentication.
I have a node.js backend, and angular and static page front end (two front ends).
My node backend accepts username and password for authentication on my route
as a post request http://localhost:3000/users/login
My journey is as follows:
1. User is presented with a static front end login page, (this is designed by injecting vue.js with axios on a static html page), wherein he requests a log in with his credentials. The client frontend is hosted on http://localhost:3011/
2. The application will now send a post request to http://localhost:3000/users/login to verify the credentials.
3. If the credentials are valid, the server will create a new session (express-session) using req.session. In this session, I also store my token that I use to authenticate the user for any subsequent requests (this token is saved in the db and verified for all further requests). The server will then respond with a 200 OKAY status.
4. Once the vue application gets a positive response, the client will redirect the application to http://localhost:3000/ where I have angular application in the dist folder.
If, in POSTMAN, I do a post to http://localhost:3000/users/login and then do a GET on http://localhost:3000/, I can see the token in the logs when the server responds to the GET request.
But, if i send a post request to http://localhost:3000/users/login from my vue application, and then redirect to http://localhost:3000/ on successful authentication, I cannot see the token in the logs.
Code Snippet on the client side (Vue)
submit() {
this.errMsg = "";
axios
.post("http://localhost:3000/users/login", {
user: this.user,
password: this.password
})
.then(response => {
window.location = "http://localhost:3000/";
})
.catch(err => {
console.log(err);
this.errMsg = err.data.statusText;
});
}
Code inside login on server side
router.route("/login").post((req, res) => {
let { user, password } = req.body;
merchant_table
.findOne({ attributes: ["id"], where: { email, password } })
.then(result => {
if (result) {
let token = 12345;
token_table
.create({ m_id: result.id, token })
.then(result => {
req.session.user = result.token;
console.log("session is", req.session); //THIS SHOWS THE TOKEN
res.status(200).json({status:"OKAY!"})
});
} else {
res.status(401).json({status:"Invalid User!"})
}
})
.catch(error => console.log(error));
});
Code inside the request API for http://localhost:3000/
app.use("/", function(req, res) {
console.log("Session is", req.session); //THIS SHOWS THE TOKEN FOR POSTMAN, NOT WHEN WORKING WITH VUE
res.sendFile(__dirname + "/dist/index.html");
});
Since the axios post request and the subsequent redirect is to http://localhost:3000/ I expected the token to be maintained. But it seem to assume this as a new connection. Is this approach wrong? Is there a way to keep track of the token on redirect? I need the token only once, because then I will store it in the angular application and send it for any other requests that I need.
How do I go about with this?

Save jwt to local storage

I'm currently developing a node express postgresql application, and I'm trying to implement Jsonwebtokens as authentication. I've seen multiple tutorials on how to implement it and I get how to do it on the backend part, but the frontend is usually skipped and apparently everyone just tests their code with Postman.
I have also read online that the recommended way to implement jwt authentication is to store the generated token in localstorage, and, when needed, to send it on the header. But I wasn't able to find how this is done...
Thus, my questions are:
How do you store the token on the front-end once it's generated by the backend? (an example would help a lot, because I don't really get how am I supposed to get the token on a front-end javascript program)
How do you send the token on the headers when making an http request that needs it once you have it stored?
On the server side, once you have created the token and logged the user in, you send the token via res.send(), example below, note that you may have different approach to functions findByCredentials ad genereateAuthToken, they are custom:
app.post("/users/login", async (req, res) => {
try {
const user = await User.findByCredentials(
req.body.email,
req.body.password
);
const token = await user.generateAuthToken();
res.send({ token: user.tasks });
} catch (e) {
res.status(400).send();
}
});
On the frontend you can use html5's fetch() to send the token in the header. For example, if you would like to access '/users/me' that needs authentication you follow the steps below (make sure you however you save the token to localstorage first so you can access that via getItem:
localStorage.setItem('userInfo', JSON.stringify(userInfo));
document.getElementById("my-profile").addEventListener("click", getMe);
then:
function getMe(e) {
e.preventDefault();
var token = JSON.parse(localStorage.getItem('token'));
console.log(`Authorization=Bearer ${token}`)
fetch('/users/me', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token
}
})
.then(res => res.json())
.then(data => {
console.log(data)
// window.location.href = 'http://localhost:3000/dashboard';
})
.catch(err => { console.log(err) })
}
As you said, usually the token is store in localStorage.
localStorage is similar to sessionStorage, except that while data
stored in localStorage has no expiration time, data stored in
sessionStorage gets cleared when the page session ends — that is, when
the page is closed.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
For getting the token in front-end you send to a URL the email & password of the user in order to exchange it with a token (you have to be in https). After that you store it with localStorage.setItem('key', value)
Short example:
$.post("/authenticate", {email: userEmail, password: userPassword}, function(data) {
localStorage.setItem('token', data.token)
});
For get back the token, after a refresh for example, you have to use : localStorage.getItem('key').
And finally, in order to be authenticate with this token, you can send it in bearer headers in Authorization headers property.
Why bearer ? => https://security.stackexchange.com/questions/108662/why-is-bearer-required-before-the-token-in-authorization-header-in-a-http-re
Example:
$.ajax({
type: 'GET',
url: '/account,
headers: {
"Authorization": "Bearer " + token
}
}, function(data) {
// Authenticated data
});
May this can help : https://github.com/auth0-blog/angularjs-jwt-authentication-tutorial/blob/master/frontend/login/login.js

How to show different page if user is logged in via firebase

I have a slight problem, and it seems to be an easy one, but I cannot seem to wrap my head around what to do.
I have an express app, that uses Firebase to store data. I am able to login, register and log out trough a client side script, but my problem is: How do I check via express if a user is logged in, to be able to send a different page to the logged in users?
This is my code so far:
var firebase = require('firebase');
// Initialize Firebase
var config = {
serviceAccount: "./Chat Application-ad4eaaee3fcc.json",
databaseURL: "MY_DATABASE_URL"
};
firebase.initializeApp(config);
and then I want to show a special page for logged in users, and this is what I have tried:
router.get("/special-page", function(req, res, next) {
var user = firebase.auth().currentUser;
console.log(user); // this variable gets undefined
if(user) {
res.render("special-page");
} else {
res.redirect("/");
}
});
I know this might seem like an easy question, but any help would be much appreciated!
Thanks in advance.
The user side, and server side, are completely different execution areas. Hence, as you probably guessed, calling firebase.auth().currentUser on the server cannot work if the authentication occurred on the client.
The server process just does not have this information, unless the client tells him.
You could just have a request header telling "i am logged as XXX", but it would not be secure, because the server would not be able to verify that information, and a malicious user could pretend to be another one.
The only solution to this, in your use case, is to provide the Firebase token to the server, and then the server needs to verify this token against firebase server, and only then it will be 100% sure about the client authentication.
I needed that in my React app for Server Side Rendering, here is how I did it.
Upon user authentication, set a cookie that contains the firebase token
Unset the cookie when the users logs out
In the server, read the cookie to authenticate client user at each request
Code in the client :
const setAppCookie = () => firebase.auth().currentUser &&
firebase.auth().currentUser.getToken().then(token => {
cookies.set('token', token, {
domain: window.location.hostname,
expire: 1 / 24, // One hour
path: '/',
secure: true // If served over HTTPS
});
});
const unsetAppCookie = () =>
cookies.remove('token', {
domain: window.location.hostname,
path: '/',
});
// triggered by firebase auth changes, this is where you deal
// with your users authentication in your app
fbAuth.onAuthStateChanged(user => {
if (!user) {
// user is logged out
return;
}
// user is logged in
setAppCookie();
// Reset cookie before hour expires
// (firebase tokens are short lived, say the docs)
setInterval(setAppCookie, 3500);
});
[...]
// In the logout code
unsetAppCookie();
Code in the server:
// Before serving express app, enable cookie parsing
app.use(cookieParser());
// In the code dealing with your requests
const { token } = req.cookies;
if (!token) {
// renderWithoutUser();
}
//
// If user found in cookie, verify the token and render with logged in store
//
console.log('Verifying token', token);
firebase.auth().verifyIdToken(token)
.then(decodedToken => {
const uid = decodedToken.sub;
console.log('User is authenticated for this request', uid);
// renderWithUser();
})
.catch(err => {
console.error('WARNING token invalid or user not found', err);
// renderWithoutUser();
});

Resources