Authentication for protected routes using express/jwt - express

When the user logins, the access token is created and sent to the user, it is then stored in sessionStorage. Everything before this works fine. My problem is that I do not know how to use the access token to gain access to protected routes.
express app.js (smoothies is the protected route)
app.get('/smoothies', requireAuth, (req, res) => res.render('smoothies'));
authMiddleware.js
const User = require('../models/User');
const requireAuth = (req, res, next) => {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
// check json web token exists & is verified
if (token) {
jwt.verify(token, 'night of fire', (err, decodedToken) => {
if (err) {
console.log(err.message);
res.redirect('/login?err=auth');
} else {
console.log(decodedToken);
next();
}
});
} else {
res.redirect('/login?err=auth');
}
};
// check current user
module.exports = { requireAuth };
smoothies.ejs
var myHeaders = new Headers();
myHeaders.append("Authorization", `Bearer ${token}`);
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("http://localhost:3000/smoothies", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
//Should I be even doing this fetch GET request on smoothie.ejs?
})
Smoothies is the protected route. When I try to use Postman and send a GET request to (/smoothies) using authorization : bearer token, it works and I am able to access /smoothies. However, if I try on the real application, I was denied access even with access token in my sessionStorage. When I console.log req.headers['authorization'], it was undefined so I am guessing my GET request from smoothie.ejs does not work. Does anyone know what is the solution?

Related

How to redirect to login page if JWT is not valid, using Express with API

I've built an Express app that contains an API and a front end. By using Axios the front end can request data (e.g. a user-object or a todo-object) from the API, which will validate the offered JWT with its middleware. If the jwt.verify() errs, the protected routes won't fire. This all works fine.
My question is: how do I set up the front end such that any page-request will redirect to a login page if the browser-stored JWT is not valid (excluding the login and register pages, to prevent circular redirection)? Do I have to preface every .ejs-file with an Axios.post() that sends the browser-stored JWT for verification, or is there a best practice that I am missing?
My goal, when an invalid JWT is offered, is to have the API routes return a json-object (e.g. { err: "invalid token offered" }), and to have all the front end routes redirect the user to the login page.
Some sample code below.
server.js
// API Routes
app.use('/api/todos', CheckToken, APITodosRouter)
app.use('/api/auth', APIAuthRouter)
// Front-end Routes
app.use('/', indexRouter)
app.use('/todos', todosRouter)
app.use('/auth', authRouter)
todos.ejs (This works fine)
// get todos from db
let todosData
const getTodos = async () => {
let response = await axios.get('/api/todos/all', {
headers: {
'Content-Type': 'application/json',
'authorization': `Bearer ${localStorage.access_token}`
}
})
if (!response) return console.log({ msg: "no response received."})
if (!response.data) return console.log({ msg: "no data received."})
if (!response.data.payload) return console.log({ msg: "no todos found."})
todosData = response.data.payload
}
// boot page
;(async () => {
await getTodos()
renderTodos() // a function that reads todosData updates the DOM accordingly
})()
checkToken.js (Middleware)
const jwt = require('jsonwebtoken')
const checkToken = (req, res, next) => {
const ah = req.headers.authorization
const token = ah && ah.split(' ')[1]
if (!token) return res.json({ msg: "No token offered."})
jwt.verify(token, process.env.TOKEN_SECRET, (err, user) => {
if (err) return res.json({ msg: "Invalid token offered."})
req.user = user
next()
})
}
module.exports = checkToken

setting cookie after google passport callback

I am using facebook and google oauth2 login using passport js, with this flow
User clicked the login button
Redirects to facebook/google auth page (depending on what login the user chooses)
The auth page redirects back to a callback page (/auth/callback/[provider])
A passport express middleware will catch it to parse some data and then send it to a remote api of myown to sign the user in
The auth remote api will send a response back consisting the user token
A custom express middleware will catch the response to set cookie on the server
the express chain ends by route it to /profile (cookie with token is set on the browser)
/profile will then checks if there is a token, if there is not: it will redirect to /
Doing this flow on facebook login is fine, the user is successfully redirected to /profile, with all of its data and token, the google oauth2 login however seems to be doing the redirect to /profile then setting the token (step #7 then #6), so everytime the user is using google oauth2 login, its always gonna be redirected back to / since by the time it arrives at /profile, it doesnt have the token
here's the code on the above's flow
#./server.js
const express = require('express')
const next = require('next')
const Passport = require('./server/middleware/passport')
const Api = require('./server/api')
const port = parseInt(process.env.PORT, 10)
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app
.prepare()
.then(() => {
const server = express()
// ... other unrelated things
server.use(Passport.initialize())
Api.passport.facebook(server)
Api.passport.facebookCallback(server)
Api.passport.google(server)
Api.passport.googleCallback(server)
// ... other unrelated things
server.all('*', (req, res) => handle(req, res))
server.listen(port, (error) => {
if (error) throw error
// ... other unrelated things
})
})
#./server/api.js
const Passport = require('middleware/passport')
function setCookie(req, res, next) {
res.cookie('token', req.user.auth.token, {
httpOnly: true,
sameSite: 'strict',
path: '/',
secure: process.env.NODE_ENV !== 'development',
})
next()
}
function facebook(app) {
return app.get('/auth/facebook', (req, res, next) => {
Passport.authenticate('facebook', {
scope: ['email', 'public_profile']
})(req, res, next)
})
}
function facebookCallback(app) {
return app.get(
'/auth/callback/facebook',
Passport.authenticate('facebook', { session: false, failureRedirect: '/' }),
setCookie,
(req, res) => {
res.redirect('/profile')
},
)
}
function google(app) {
return app.get('/auth/google', (req, res, next) => {
Passport.authenticate('google', {
scope: [
'https://www.googleapis.com/auth/userinfo.email ',
'https://www.googleapis.com/auth/userinfo.profile ',
],
prompt: 'consent',
authType: 'rerequest',
accessType: 'offline',
})(req, res, next)
})
}
function googleCallback(app) {
return app.get(
'/auth/callback/google',
Passport.authenticate('google', { failureRedirect: '/', session: false }),
setCookie,
(req, res) => {
res.redirect('/profile')
},
)
}
module.exports = {
passport: {
facebook,
facebookCallback,
google,
googleCallback,
}
}
#./server/middleware/passport.js
const axios = require('axios')
const passport = require('passport')
const GoogleStrategy = require('passport-google-oauth20').Strategy
const FacebookStrategy = require('passport-facebook').Strategy
passport.serializeUser((user, done) => {
done(null, user)
})
passport.deserializeUser((obj, done) => {
done(null, obj)
})
function verifyCallback(req, ... , done) {
process.nextTick(async () => {
try {
const options = {
baseURL: baseUrl, // My remote api url
method: 'POST',
url: '/auth/signin',
headers: {
'Content-Type': 'application/json',
},
data: JSON.stringify({
// email, fullname, etc
}),
}
const response = await axios(options)
return done(null, response.data)
} catch (error) {
const { response } = error
return done(JSON.stringify(response.data, null, 2), null)
}
})
}
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: callbackURLGoogle,
passReqToCallback: true,
}, verifyCallback))
passport.use(new FacebookStrategy({
clientID: process.env.FACEBOOK_CLIENT_ID,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
callbackURL: callbackURLFacebook,
enableProof: true,
profileFields: ['id', 'name', 'email', 'picture.type(large)'],
passReqToCallback: true,
}, verifyCallback))
module.exports = passport
I console.log() things, just to figure out if it falls to the correct sequence of flow, the console doesn't seem to log anything suspicious, is there's something i am missing here?
PS: i am also using next js with custom server
I was facing the same problem and was able to send cookies by using custom callback.
router.get('/google/callback', (req, res) => {
passport.authenticate('google', {session: false, failureRedirect:'/auth/google/failure'},
async(err, user) => {
// You can send cookies and data in response here.
})(req, res)
})
Please refer custom callback section in documentation for explanation.

Cookie blocked by Chrome

I am trying to set up a simple register/login form with vuejs in the front and a server with express js using the passport library to setup a local and social media startegy.
But I can't seem to pass cookies to the front end when I login with the local strategy.
Also when I sign in with google I get the cookie on the front end but it is not sent with the next API call but this is a subject for another question.
I was confused by this so I made a simple project just to receive and send cookies and it works. Here is the back end:
//headers in app.js
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
// index file
router.get('/cookie', function (req, res, next) {
res.cookie("token", "mytoken");
res.send("cookie sent");
});
router.get('/info', function (req, res, next) {
cookies = req.cookies;
console.log(cookies);
res.cookie("token", "mytoken");
res.send("cookie sent");
});
And here is my front end methods that call the API:
methods: {
async getCookie() {
await axios.get("http://localhost:3000/cookie",{withCredentials:true}).then((response) => {
console.log(response);
}).catch((e) => {
console.log(e);
});
},
async sendCookie() {
await axios.get("http://localhost:3000/info",{withCredentials:true}).then((response) => {
console.log(response);
}).catch((e) => {
console.log(e);
});
}
}
With that I have no problem passing the cookie in the requests and receiving it.
Now on my real project I have this on the back end
//Headers just like the other project
router.post('/users/login', function (req, res, next) {
passport.authenticate('local', { session: false }, function (err, user, info) {
if (err) { return next(err); }
if (user) {
res.cookie('token', 'mytoken');
return res.json({ user: user.toAuthJSON() });
} else {
return res.status(401).json(info);
}
})(req, res, next);
});
Front end call:
// Service file to call the api
axios.defaults.baseURL = "http://127.0.0.1:3000/api/";
axios.defaults.withCredentials = true;
const ApiService = {
get(resource, slug = "") {
return axios.get(`${resource}/${slug}`).catch(error => {
throw new Error(`ApiService ${error}`);
});
},
...
}
export default ApiService;
//actual call in authetification module file
[LOGIN](context, credentials) {
return new Promise(resolve => {
ApiService.post("users/login", { email: credentials.email, password: credentials.password })
.then(({ data }) => {
context.commit(SET_AUTH, data.user);
resolve(data);
})
.catch(({ response }) => {
context.commit(SET_ERROR, response.data.errors);
});
});
},
//
The request works but the cookie is blocked by Chrome:
I don't see what is the difference in my two projects that would trigger this warning on Chrome for the last one.
EDIT: In my original post axios.defaults.baseURL was not set to my actual value.
After last update of chrome browser I also started to get this error. A solution to solve this go to chrome://flags and disable SameSite by default cookies and disable Enable removing SameSite=None cookies. This will solve your problem. I think another way to solve this changing your cookie settings(samesite attribute) when you are creating your session.
Find the solution thank to #skirtle. I set axios.defaults.baseURL to "http://127.0.0.1:3000/api/" but localhost and 127.0.0.1 are not interchangeable and considered two different domains. I switched to axios.defaults.baseURL = "http://localhost:3000/api" and it fixed the problem.

Get AWS Cognito user from ID Token retrieved from Token Endpoint

I am building a React Native app using Expo and AWS Cognito with AWS Amplify, and I am trying to enable signing in with Facebook, Google, etc. using AWS
I can create a user and sign in using Cognito APIs without any issue.
Using third-parties, though, requires using the Expo AuthSession functionality.
The functionality itself works fine, and I am able to get all the way to retrieving the proper tokens from my /oauth2/token endpoint.
However, as far as Amplify is concerned (and I am aware), the user is not signed in, so when I try to get Auth.currentAuthenticatedUser(), null is returned.
// Open URL in a browser
openURL = async (url) => {
let result = await AuthSession.startAsync({ authUrl: url })
this.getTokenbyCode(result.params.code)
};
getTokenbyCode = async (code) => {
const details = {
grant_type: 'authorization_code',
code,
client_id: '10eavoe3ufj2d70m5m3m2hl4pl',
redirect_uri: AuthSession.getRedirectUrl()
}
const formBody = Object.keys(details)
.map(
key => `${encodeURIComponent(key)}=${encodeURIComponent(details[key])}`
)
.join("&");
await fetch(
'https://presentor.auth.us-west-2.amazoncognito.com/oauth2/token',
{
method: "POST",
headers: {
'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: formBody
}
)
.then(async (res) => {
console.log('res: ', res);
let resJSON = await res.json();
let idToken = await resJSON.id_token;
let decodedToken = jwt(idToken);
let userData = {
Username : decodedToken["cognito:username"],
Pool : Auth.userPool
}
})
.catch(error => {
console.log('error: ', error);
});
}
When I decode the token, I see the payload as I expect, but if I want to, for example, utilize the APIs to refresh the token if it expires, I have to workaround manually (check for expiration and retrieve a new token if it's expired).
Am I missing something basic?
Ok, I figured it out. Not sure if this is the right path, but it's pretty clean and it works, so I'm good with it.
Create CognitoIdToken, CognitoAccessToken, and CognitoRefreshToken objects using amazon-cognito-identity-js
Create a user session from those tokens
Create a user from that user session
await fetch(
'TOKEN ENDPOINT',
{
method: "POST",
headers: {
'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: formBody
}
)
.then(async (res) => {
const IdToken = new CognitoIdToken({ IdToken: tokenRequestJson.id_token });
const AccessToken = new CognitoAccessToken({ AccessToken: tokenRequestJson.access_token });
const RefreshToken = new CognitoRefreshToken({ RefreshToken: tokenRequestJson.refresh_token })
try {
let userSession = new CognitoUserSession({ IdToken, AccessToken, RefreshToken });
console.log('userSession: ', userSession);
const userData = {
Username: userSession.idToken.payload.email,
Pool: userPool
};
console.log('userData: ', userData);
cognitoUser = new CognitoUser(userData);
cognitoUser.setSignInUserSession(userSession);
cognitoUser.getSession((err, session) => { // You must run this to verify that session (internally)
if (session.isValid()) {
console.log('session is valid');
this.setState({user: cognitoUser})
this.props.navigation.navigate('AuthLoading')
} else {
console.log('session is not valid: ', session);
}
})
}
catch (FBSignInError) {
console.log('FBSignInError: ', FBSignInError)
}
})
.catch(fetchError => console.log('fetchError: ', fetchError))

How can I share data between routes on the request object in Express?

I'm working on an application that authenticates with Spotify's API. I am using passport-spotify to do so. I need to be able to access a session ID a my root route (/).
While I'm able to set the session id during the /callback after authentication with Spotify, I can't then access the session id at /. Can someone please explain to me how to pass data between routes in Express so that I can access req.session.id in / after I've authenticated?
I'll share my endpoints here:
/
app.get('/', cors(), (req, res) => {
if (req.session.id != null) {
res.json({isAuthenticated: true })
} else {
res.json({isAuthenticated: false, message: 'Please log in.' })
}
})
Passport Strategy
passport.use(new SpotifyStrategy({
clientID: clientId,
clientSecret: clientSecret,
callbackURL: CALLBACK_URL
},
(accessToken, refreshToken, profile, done) => {
process.nextTick(function () {
let user = { spotifyId: profile.id, access_token: accessToken,
refresh_token: refreshToken }
return done(null, user)
})
}))
/auth/spotify
app.get('/auth/spotify',
passport.authenticate('spotify', {scope: ['user-read-email', 'user-
read-private'], showDialog: true}),
(req, res) => {
})
/callback
app.get('/callback', passport.authenticate('spotify', {
failureRedirect: '/', successRedirect: FRONTEND_URL }), (req, res,
next) => {
req.session.id = req.user.spotifyId
localStorage.setItem('access_token_' + req.session.id,
req.user.access_token)
localStorage.setItem('refresh_token_' + req.session.id,
req.user.refresh_token)
return next(null, req.session.id)
})
There is no way to share data in the way you asked your question, and the reason thereof is very simple, they are 2 different req Objects.
The what you can do, is define a separate middlware function, something like this :
function middlware(req, res, next) {
req.session.id = req.user.spotifyId;
next();
}
And you call that function in both of your routs as a middlware after the Spotify middlware.