Keystonejs with Oauth2 has no return - keystonejs

I am using KeystoneJS and wanna insert the oauth2 codes.
All my Token and Users codes are run very fine; the methods are triggered via console.log. The token is generated successfully.
However, there is no return and finally I receive a timeout in my client:
// Setup Route Bindings
exports = module.exports = function(app) {
// Oauth2
var oauth = oauthserver({
model: require('../models/Client'),
grants: ['password', 'refresh_token'],
debug: true });
// Views
app.get('/', routes.views.index);
// both routes below can be triggered correctly, but timeout return
app.all('/oauth/token', oauth.grant());
app.get('/secret', oauth.authorise(), function (req, res) {
res.send('Secret area');
});
};

Related

Grant Provider OAuth state mismatch when accessing the two application modules simultaneously on same browser and user is not logged in yet

I have been trying to implement Single SignOn(SSO). I have different frontend application modules which are running on different domain and they all utlize a single API server.
SSO Server https://sso.app.com
API Server https://api.app.com
Frontend Module 1 https://module-1.app.com
Frontend Module 2 https://module-2.app.com
Authentication flow
The flow of authentication is FrontEnd Module check for token in the localstorage. If it do not find the token, it redirect the user to API server endpoint let say https://api.app.com/oauth/connect.
API server has the clientId and Secrets for the SSO server. API server set the url of Frontend module in the cookie(so that i can redirect the user back to initiator frontend module) and then redirect the request to SSO server where user is presented with login screen. User enters the creds there, SSO server validate the credientials, creates a session.
Once credientials are validated, SSO server calls the API server Endpoint with user profile and access_token. API server gets the profile in the session and query and sign its own token and send that to frontend module through query params. On the frontEnd(React APP) there is a route just for this. In that frontend route I extract the token from queryParams and set in the localstorage. User is in the application.
Similarly when user loads the FrontendModule-2 same flow happend but this time because Session is being created by SSO server when FrontendModule-1 flow ran. it never ask for login creds and sign the user in to the system.
Failing Scenario:
The scenario is, assume there is user JHON who is not logged in yet and do not have session. Jhon hit the "Frontend Module 1" URL in the browser. Frontend module check the localStorage for the token, it do not find it there, then Frontend module redirect the user to API server route.
API server has the clientSecret and clientId which redirect the request to SSO server. There user will be presented with Login Screen.
Jhon sees the login screen and left it as it is. Now Jhon opens another tab in the same browser and enter the URL of "Frontend Module 2". Same flow happen as above and Jhon lands on login screen. Jhon left that screen as it is and moves back to the first tab where he has Frontend Module 1 session screen loaded up. He enter the creds and hit the login button. It give me error that session state has been changed.
This error actually makes sense, because session is a shared.
Expectation
How do I achieve this without the error. I want to redirect the user to the same Frontend Module which initiated the request.
Tools that I am Using
NodeJS
grant-express
express-session
Sample Implementation (API Server)
require('dotenv').config();
var express = require('express')
, session = require('express-session')
, morgan = require('morgan')
var Grant = require('grant-express')
, port = process.env.PORT || 3001
, oauthConsumer= process.env.OAUTH_CONSUMER || `http://localhost`
, oauthProvider = process.env.OAUTH_PROVIDER_URL || 'http://localhost'
, grant = new Grant({
defaults: {
protocol: 'https',
host: oauthConsumer,
transport: 'session',
state: true
},
myOAuth: {
key: process.env.CLIENT_ID || 'test',
secret: process.env.CLIENT_SECRET || 'secret',
redirect_uri: `${oauthConsumer}/connect/myOAuth/callback`,
authorize_url: `${oauthProvider}/oauth/authorize`,
access_url: `${oauthProvider}/oauth/token`,
oauth: 2,
scope: ['openid', 'profile'],
callback: '/done',
scope_delimiter: ' ',
dynamic: ['uiState'],
custom_params: { deviceId: 'abcd', appId: 'com.pud' }
}
})
var app = express()
app.use(morgan('dev'))
// REQUIRED: (any session store - see ./examples/express-session)
app.use(session({secret: 'grant'}))
// Setting the FrontEndModule URL in the Dynamic key of Grant.
app.use((req, res, next) => {
req.locals.grant = {
dynamic: {
uiState: req.query.uiState
}
}
next();
})
// mount grant
app.use(grant)
app.get('/done', (req, res) => {
if (req.session.grant.response.error) {
res.status(500).json(req.session.grant.response.error);
} else {
res.json(req.session.grant);
}
})
app.listen(port, () => {
console.log(`READY port ${port}`)
})
You have to redirect the user back to the originating app URL not the API server URL:
.use('/connect/:provider', (req, res, next) => {
res.locals.grant = {dynamic: {redirect_uri:
`http://${req.headers.host}/connect/${req.params.provider}/callback`
}}
next()
})
.use(grant(require('./config.json')))
Then you need to specify both:
https://foo1.bar.com/connect/google/callback
https://foo2.bar.com/connect/google/callback
as allowed redirect URIs of your OAuth app.
Lastly you have to route some of the app domain routes to your API server where Grant is handling the redirect URI.
Example
Configure your app with the following redirect URI https://foo1.bar.com/connect/google/callback
Navigate to https://foo1.bar.com/login in your browser app
The browser app redirects to your API https://api.bar.com/connect/google
Before redirecting the user to Google, the above code configures the redirect_uri based on the incoming Host header of the request to https://foo1.bar.com/connect/google/callback
The user logs into Google and is being redirected back to https://foo1.bar.com/connect/google/callback
That specific route have to be redirected back to your API https://api.bar.com/connect/google/callback
Repeat for https://foo2.bar.com
you have relay_state option while hitting SSO server, that is returned as it was sent to SSO server, just to keep track of application state before requesting SSO.
TO learn more about relay state: https://developer.okta.com/docs/concepts/saml/
And which SSO service are you using??
The way I solved this problem by removing the grant-express implementation and use the client-oauth2 package.
Here is my implementation.
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
const session = require('express-session');
const { JWT } = require('jose');
const crypto = require('crypto');
const ClientOauth2 = require('client-oauth2');
var logger = require('morgan');
var oauthRouter = express.Router();
const clientOauth = new ClientOauth2({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.SECRET,
accessTokenUri: process.env.ACCESS_TOKEN_URI,
authorizationUri: process.env.AUTHORIZATION_URI,
redirectUri: process.env.REDIRECT_URI,
scopes: process.env.SCOPES
});
oauthRouter.get('/oauth', async function(req, res, next) {
try {
if (!req.session.user) {
// Generate random state
const state = crypto.randomBytes(16).toString('hex');
// Store state into session
const stateMap = req.session.stateMap || {};
stateMap[state] = req.query.uiState;
req.session.stateMap = stateMap;
const uri = clientOauth.code.getUri({ state });
res.redirect(uri);
} else {
res.redirect(req.query.uiState);
}
} catch (error) {
console.error(error);
res.end(error.message);
}
});
oauthRouter.get('/oauth/callback', async function(req, res, next) {
try {
// Make sure it is the callback from what we have initiated
// Get uiState from state
const state = req.query.state || '';
const stateMap = req.session.stateMap || {};
const uiState = stateMap[state];
if (!uiState) throw new Error('State is mismatch');
delete stateMap[state];
req.session.stateMap = stateMap;
const { client, data } = await clientOauth.code.getToken(req.originalUrl, { state });
const user = JWT.decode(data.id_token);
req.session.user = user;
res.redirect(uiState);
} catch (error) {
console.error(error);
res.end(error.message);
}
});
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'My Super Secret',
saveUninitialized: false,
resave: true,
/**
* This is the most important thing to note here.
* My application has wild card domain.
* For Example: My server url is https://api.app.com
* My first Frontend module is mapped to https://module-1.app.com
* My Second Frontend module is mapped to https://module-2.app.com
* So my COOKIE_DOMAIN is app.com. which would make the cookie accessible to subdomain.
* And I can share the session.
* Setting the cookie to httpOnly would make sure that its not accessible by frontend apps and
* can only be used by server.
*/
cookie: { domain: process.env.COOKIE_DOMAIN, httpOnly: true }
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/connect', oauthRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
In my /connect/oauth endpoint, instead of overriding the state I create a hashmap stateMap and add that to session with the uiState as a value received in the url like this https://api.foo.bar.com?uiState=https://module-1.app.com
When in the callback I get the state back from my OAuth server and using the stateMap I get the uiState value.
Sample stateMap
req.session.stateMap = {
"12313213dasdasd13123123": "https://module-1.app.com",
"qweqweqe131313123123123": "https://module-2.app.com"
}

How to properly authenticate and use GoogleCalendar-API using oAuth2 in Vue CLI environment

I'm trying to integrate Google-Calendar-API in my Vue-CLI-based Webapp. I have decided to use the node.js version of GoogleAPI as learned from this site: https://developers.google.com/calendar/quickstart/nodejs#troubleshooting. However, I got:
TypeError: Expected input to be a Function or Object, got
undefined
This is for my personal project written in Vue-Cli, Vue Router, Vuetify.js, and additionally authenticated through Firebase (login via Google account). After a user logs in through Firebase UI (via Google account), they will get access to the dashboard page where they shall be able to access their calendar via Google's oAuth2 API system (stuck). I have initially tried using the browser-based javascript API but failed (and personally preferred node.js version later).
Dashboard.vue
<script>
import { config } from "#/../hidden/config.js";
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = '#/assets/token.json';
export default {
data() {
return {
oAuth2Client: null,
SCOPES: ['https://www.googleapis.com/auth/calendar.readonly'],
client_secret: "",
client_id: "",
redirect_uris: ""
};
},
methods: {
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
authorize: () => {
const self = this;
self.oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
self.getAccessToken(self.oAuth2Client);
self.oAuth2Client.setCredentials();
self.listEvents(oAuth2Client);
},
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* #param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback for the authorized client.
*/
getAccessToken: () => {
const self = this;
const authUrl = self.oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
self.oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
self.oAuth2Client.setCredentials(token);
// self.listEvents();
});
}
/**
* Lists the next 10 events on the user's primary calendar.
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
/*
listEvents: () => {
const self = this;
const auth = self.oAuth2Client;
const calendar = google.calendar({version: 'v3', auth});
calendar.events.list({
calendarId: 'primary',
timeMin: (new Date()).toISOString(),
maxResults: 10,
singleEvents: true,
orderBy: 'startTime',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const events = res.data.items;
if (events.length) {
console.log('Upcoming 10 events:');
events.map((event, i) => {
const start = event.start.dateTime || event.start.date;
console.log(`${start} - ${event.summary}`);
});
} else {
console.log('No upcoming events found.');
}
});
}
*/
},
created: function() {
const {credentials} = require("#/credentials.json");
this.client_secret = credentials.installed.client_secret;
this.client_id = credentials.installed.client_id;
this.redirect_uris = credentials.installed.redirect_uris;
//this.authorize();
}
};
</script>
I expect to be able to connect to the Google Calendar API and start working on actually manipulating the calendar event info for my purpose. However, I'm getting the error:
TypeError: Expected input to be a Function or Object, got
undefined
.
I have tried looking for people with similar problems online, however I didn't find any video guides or written guides for Vue-cli projects that use Google APIs.
I do confess that I have modified my code a little bit from the referenced sample from the website to avoid using fs and readline npm packages. However, the error message was same in those cases too.

Can I use passport-jwt conditionally?

Meaning, in my application, I want to check if a customId is present in the client request. If yes, I will proceed authentication using that with my custom logic.
If customId is not present, I want to use passport-jwt authentication.
passport registers its initialize method at server startup itself.
My specific question is how do I use passport.authenticate only if customId is not present.
Any help is much appreciated.
Yeah you can, it's all just middleware! Here's an example of how you would do it, I've not run this code so it may not build but it shows how to do what you're after.
const express = require('express');
const passport = require('passport');
const passportJWT = require('passport-jwt');
// My express application where I setup routers, middleware etc
const app = express();
// Initialise passport
app.use(passport.initialize());
// Setup my passport JWT strategy, this just setups the strategy it doesn't mount any middleware
passport.use(new passportJWT.Strategy({
secretOrKey: '',
issuer: '',
audience: '',
}, (req, payload, done) => {
doSomeFancyAuthThingy(payload, (err, user) => {
done(err, user);
});
}));
// Now create some middleware for the authentication
app.use((req, res, next) => {
// Look to see if the request body has a customerId, in reality
// you probably want to check this on some sort of cookie or something
if (req.body.customerId) {
// We have a customerId so just let them through!
next();
} else {
// No customerId so lets run the passport JWT strategy
passport.authenticate('jwt', (err, user, info) => {
if (err) {
// The JWT failed to validate for some reason
return next(err);
}
// The JWT strategy validated just fine and returned a user, set that
// on req.user and let the user through!
req.user = user;
next();
});
}
});
As you can see the main thing you're looking for is where we create the middleware. Here we just create our own middleware and run a check (the if statement), if it fails then we run passport.authenticate which triggers the strategy we created on the passport.use block.
That will allow you to conditionally do any sort of authentication with Passport!

benefit of deserializeUser method in passport.js

I have just started with passport.js. From this article, I got what is the flow of all the passport methods and implemented the same in my application and it is working. Here is my server.js and I am using passport-local strategy. Angular app and rest APIs on the same server
import { registerControllersFromFolder } from 'giuseppe';
import { MessageManager } from './messaging/MessageManager';
import express = require('express');
import bodyParser = require('body-parser');
import session = require("express-session");
import http = require('http');
// class to hold user info
class User {
userId: number;
userName: string;
constructor(userId: number, userName: string) {
this.userId = userId;
this.userName = userName;
}
}
// server class to create http server
export class Server {
// list of apis for which authentication is not required
private static publicApiList: string[] = ["/services/login", "/login", "/favicon.ico"];
// request interceptor that will check user authentication
private static isAuthenticated = (req, res, next) => {
console.log("Authenticating :", req.originalUrl);
if (req.isAuthenticated() || Server.publicApiList.indexOf(req.originalUrl) > -1) {
// express routing
if (req.originalUrl.startsWith("/services")) {
console.log("Express Routing");
return next();
} else { // angular routing -> return index.html
console.log("Angular Routing");
return res.sendFile(__dirname + "/public/index.html");
}
} else {
console.log("User not authenticated.")
res.redirect('/');
}
};
static startServer() {
let userList: User[] = [new User(1, "Sunil"), new User(2, "Sukhi")];
let app = express();
// passport library
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
// middlewares
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ resave: false, saveUninitialized: true, secret: "secretKey123!!" }));
// passport middleware invoked on every request to ensure session contains passport.user object
app.use(passport.initialize());
// load seriliazed session user object to req.user
app.use(passport.session());
// Only during the authentication to specify what user information should be stored in the session.
passport.serializeUser(function (user, done) {
console.log("Serializer : ", user);
done(null, user);
});
// Invoked on every request by passport.session
passport.deserializeUser(function (user, done) {
let validUser = userList.filter(user => user.userId === user.userId)[0];
console.log("D-serializer : ", validUser);
done(null,validUser);
});
// passport strategy : Only invoked on the route which uses the passport.authenticate middleware.
passport.use(new LocalStrategy({
usernameField: 'name',
passwordField: 'password'
},
function (username, password, done) {
console.log("Strategy : Authenticating if user is valid :", username)
let user = userList.filter(user => username === user.userName);
console.log("Valid user : ", user)
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
return done(null, user[0]);
}
));
// intercept request for authentication
app.use(Server.isAuthenticated);
app.post('/services/login', passport.authenticate('local', {
successRedirect: '/profile',
failureRedirect: '/login'
}));
app.get('/services/logout', (req: any, res: any) => {
req.logout();
console.log("User Logout");
res.send("{status:'logout'}")
});
// http server creation
let server = http.createServer(app);
registerControllersFromFolder({ folderPath: './api' })
.then(router => {
app.use(router);
/* start express server */
})
.catch(err => {
/* error happened during loading and registering */
});
server.listen(7000, () => {
console.log('Up and running on port 7000');
});
}
}
exports.startServer = Server.startServer;
// Call a module's exported functions directly from the command line.
require('make-runnable');
When I hit localhost:7000 it serves the index.html page as I have used
app.use(express.static(__dirname + "/public"));
and this is an angular app and because of angular routing login module will get loaded by default. I have used a middleware that checks request authentication and if true then based on request prefix (angular or express) routing is done.
For the login request defined local strategy method is called and if this is true it calls serializer method that takes the responsibility which data should be stored in the request session. and then sucessRedirect or failureRedirect is called.
For subsequent request, As I have used middleware that checks if req.isAuthenticated is true if so then request is served otherwise the user is redirected to login page. I know in every subsequent request deserializeUser method is called that contains the object that was stored by serializeUser method in the login request. As per the document, this makes a call to the database to check valid user.
But I am confused but is the actual use case of deserializeUser method? Where can I take the benefit of this method and if I am intercepting ecah request and check req.isAuthenticted() then why to call database in deserializeUser method?>
As stated in this answer
The first argument of deserializeUser corresponds to the key of the
user object that was given to the done function (see 1.). So your
whole object is retrieved with help of that key. That key here is the
user id (key can be any key of the user object i.e. name,email etc).
In deserializeUser that key is matched with the in memory array /
database or any data resource.
The fetched object is attached to the request object as req.user
Thus, the benefit of deserializeUser is that you have the user object available on every request thereafter.
You ask why you need to use deserializeUser if you call req.isAuthenticated, and the answer lies in the implementation of req.isAuthenticated:
req.isAuthenticated = function() {
var property = 'user';
if (this._passport && this._passport.instance) {
property = this._passport.instance._userProperty || 'user';
}
return (this[property]) ? true : false;
};
To me, it looks like req.isAuthenticated is looking for req[user] to be set, and thus, deserializeUser must be called before it can work.

get current logged in user in Parse.com cloud code [duplicate]

When i use this function in Cloud Code Parse.User.current() return null.
I'm using parseExpressCookieSession for login.
Any advice?
var express = require('express');
var expressLayouts = require('cloud/express-layouts');
var parseExpressHttpsRedirect = require('parse-express-https-redirect');
var parseExpressCookieSession = require('parse-express-cookie-session');
// Required for initializing enter code hereExpress app in Cloud Code.
var app = express();
// Global app configuration section
app.set('views', 'cloud/views');
app.set('view engine', 'ejs'); // Switch to Jade by replacing ejs with jade here.
app.use(expressLayouts); // Use the layout engine for express
app.set('layout', 'layout');
app.use(parseExpressHttpsRedirect()); // Require user to be on HTTPS.
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('helloworld'));
app.use(parseExpressCookieSession({
fetchUser: true,
cookie: { maxAge: 3600000 * 24 }
}));
Parse.Cloud.beforeSave('Menu', function(request, response) {
var Business = Parse.Object.extend('Business');
var query = new Parse.Query(Business);
query.equalTo('profile', Parse.User.current().get('profile'));
query.find({
success: function(business) {
console.log(business);
response.success();
},
error: function(error) {
response.error(error.message);
}
});
});
app.listen();
This the code that i use to login/logout
app.post('/login', function(req, res) {
Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
// Login succeeded, redirect to homepage.
// parseExpressCookieSession will automatically set cookie.
res.redirect('/');
},
function(error) {
// Login failed, redirect back to login form.
res.redirect('/');
});
});
// Logs out the user
app.post('/logout', function(req, res) {
Parse.User.logOut();
res.redirect('/');
});
It is an old question but answering for future reference.
Parse.User.current() works in Javascript SDK when used in clients ex. WebApp where users log in and the you can fetch the current user with that function.
To get the user calling a Cloud Code function or doing an operation on an object (beforeSave,afterSave,beforeDelete and so on) you use the request.user property it contains the user issuing the request to Parse.com.
More details about Parse.Cloud.FunctionRequest here: https://parse.com/docs/js/api/classes/Parse.Cloud.FunctionRequest.html
Example code:
Parse.Cloud.beforeSave('Menu', function(request, response) {
var requestUser = request.user;
// instance of Parse.User object of the user calling .save() on an object of class "Menu"
// code cut for brevity
});