hapi-auth-cookie not setting cookie immediately after redirect with bell - cookies

I'm using Bell for Meetup OAuth, then persisting with hapi-auth-cookie.
Here are the relevant parts of code.
server.auth.strategy('session', 'cookie', {
cookie: 'sessionid',
password: '32_char_password',
// redirectTo: '/login', //this causes a loop immediately after allowing access
redirectTo: false,
isSecure: false,
});
server.auth.strategy('meetupauth', 'bell', {
provider: 'meetup',
password: '32_char_password',
isSecure: false,
providerParams: {
set_mobile: 'on'
},
clientId: 'client_id',
clientSecret: 'client_secret',
});
server.route({
method: ['GET'],
path: '/login',
config: {
auth: 'meetupauth',
handler: (request, reply) => {
request.cookieAuth.set({
sid: request.auth.credentials.profile
});
return reply.redirect('/user');
}
}
});
server.route({
method: 'GET',
path: '/user',
config: {
auth: 'session',
handler: (request, reply) => reply('My Account'),
}
});
The code works fine, except immediately after allowing access to Meetup. Once allowed access, the /login page redirects to /user. Not redirecting back to the login page, I get a 401, and after I reload /user the cookie is there. Once I've given access, it works fine; just the initial allow. What is happening?

Try setting the "isSameSite" variable to the "Lax" value
const options = {
connections: {
state: {
isSameSite: 'Lax'
}
}
};
const server = new Server(options);

Related

SvelteKit unable to set cookie

Using SvelteKit 1.0.0-next.571
My application has a login route with:
+page.server.ts => redirects to / if locals.user is set
+page.svelte => show login page
signin/+server.ts => Login and get a jwt from graphql app running on the same machine.
+server.ts:
[..]
let gqlResponse = await response.json();
if ( gqlResponse.errors ) {
console.log("ERRORS FROM GRAPHQL MIDDLEWARE:", gqlResponse.errors);
return json( { error: gqlResponse.errors, isException: true } );
}
if (gqlResponse.data.login.user && !gqlResponse.data.login.error) {
opts.cookies.set('jwt', gqlResponse.data.login.token, {
path: '/',
maxAge: SESSION_MAX_AGE
});
opts.setHeaders( { 'Access-Control-Allow-Credentials': 'true' } )
opts.setHeaders({ 'Content-Type': 'application/json' })
}
return json( gqlResponse.data.login );
and the login handler in +page.svelte :
[..]
const fetchOptions = {
method: 'POST',
//mode: 'no-cors',
//redirect: 'follow' as RequestRedirect,
body: JSON.stringify(credentials),
credentials: 'include' as RequestCredentials
}
try {
const response = await fetch('/login/signin', fetchOptions);
const login = await response.json();
if (login.error) {
handleError(login);
return false;
}
} catch (e) {
return handleException(e);
}
goto('/', { replaceState: true, invalidateAll: true} );
This works fine in localhost, but connecting another device to the local network does not set any cookies making impossible to login:
Local: http://localhost:5173/
➜ Network: http://192.168.x.x:5173/
I also tried with different fetch options and cookie settings like:
opts.cookies.set('jwt', gqlResponse.data.login.token, {
path: '/',
httpOnly: true,
sameSite: 'strict',
// secure: true
maxAge: SESSION_MAX_AGE
});
but no luck, and now 'm stuck.

AWS cognito not storing cookies in prod

Context:
I am using the amazon-cognito-identity-js SDK for authentication, as I am not using amplify for this project, only need to use cognito services. So far locally, I can do pretty much every fine, tokens come back and using the new AmazonCognitoIdentity.CookieStorage() it seems to be to store cookies locally using ({ domain: 'localhost', secure: 'false' }).
Also using nextjs v10.0.6
Problem
I tried to deploy the app to netlify and after installing it gives me back the tokens but does not store them in cookies on my browser.
Here is the snippet of code that I am using to sign in a user, there is a use case where the user was created by the admin, and will be forced to change password, thus the redirect to /changePassword
Any guidance would be amazing! My suspicion is that I am not configuring the domain right... but have tried every combination such as, removing the https, only including the autoGenerated subdomain part, etc
export const userPoolData = (): ICognitoUserPoolData => ({
UserPoolId: process.env.USER_POOL_ID || '',
ClientId: process.env.CLIENT_ID || '',
Storage: new CookieStorage({
domain: 'https://<autoGeneratedURL>.netlify.app',
secure: true,
expires: 10,
path: '/',
}),
});
const authenticationData = {
Username: username,
Password: password,
};
const authenticationDetails = new AuthenticationDetails(authenticationData);
const poolData = userPoolData();
const userPool = new CognitoUserPool(poolData);
console.log({ poolData });
const userData = {
Username: username,
Pool: userPool,
Storage: new CookieStorage({
domain: 'https://<autoGeneratedURL>.netlify.app',
secure: true,
expires: 10,
path: '/',
}),
};
const cognitoUser: CognitoUser = new CognitoUser(userData);
const userTokens: Pick<ResponseMessage, 'tokens'> = {};
console.log(authenticationData);
const authResponse = new Promise(() => {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
console.log(result);
router.push({ pathname: '/' });
},
onFailure: (error) => {
console.log(error);
if (error.code !== 'InvalidParameterException' && error.code !== 'NotAuthorizedException') {
router.push({ pathname: '/changePassword', query: { username, password } });
}
},
});
});
try {
await authResponse;
} catch (error) {
return {
success: false,
code: 500,
error,
};
}
In case anyone runs into this, it turned out my suspicion was right and the fault was in the domain pattern, for a netlify app it should be configured as domain: <autoGeneratedURL>.netlify.app

Set Session ID Cookie in Nuxt Auth

I have the following set up in my nuxt.config.js file:
auth: {
redirect: {
login: '/accounts/login',
logout: '/',
callback: '/accounts/login',
home: '/'
},
strategies: {
local: {
endpoints: {
login: { url: 'http://localhost:8000/api/login2/', method: 'post' },
user: {url: 'http://localhost:8000/api/user/', method: 'get', propertyName: 'user' },
tokenRequired: false,
tokenType: false
}
}
},
localStorage: false,
cookie: true
},
I am using django sessions for my authentication backend, which means that upon a successful login, i will have received a session-id in my response cookie. When i authenticate with nuxt however, i see the cookie in the response, but the cookie is not saved to be used in further requests. Any idea what else i need to be doing?
This is how I handled this, which came from a forum post that I cannot find since. First get rid of nuxt/auth and roll your own with vuex store. You will want two middleware, one to apply to pages you want auth on, and another for the opposite.
This assumes you have a profile route and a login route that returns a user json on successful login.
I'm also writing the user to a cookie called authUser, but that was just for debugging and can be removed if you don't need it.
store/index
import state from "./state";
import * as actions from "./actions";
import * as mutations from "./mutations";
import * as getters from "./getters";
export default {
state,
getters,
mutations,
actions,
modules: {},
};
store/state
export default () => ({
user: null,
isAuthenticated: false,
});
store/actions
export async function nuxtServerInit({ commit }, { _req, res }) {
await this.$axios
.$get("/api/users/profile")
.then((response) => {
commit("setUser", response);
commit("setAuthenticated", true);
})
.catch((error) => {
commit("setErrors", [error]); // not covered in this demo
commit("setUser", null);
commit("setAuthenticated", false);
res.setHeader("Set-Cookie", [
`session=false; expires=Thu, 01 Jan 1970 00:00:00 GMT`,
`authUser=false; expires=Thu, 01 Jan 1970 00:00:00 GMT`,
]);
});
}
store/mutations
export const setUser = (state, payload) => (state.user = payload);
export const setAuthenticated = (state, payload) =>
(state.isAuthenticated = payload);
store/getters
export const getUser = (state) => state.user;
export const isAuthenticated = (state) => state.isAuthenticated;
middleware/redirectIfNoUser
export default function ({ app, redirect, _route, _req }) {
if (!app.store.state.user || !app.store.state.isAuthenticated) {
return redirect("/auth/login");
}
}
middleware/redirectIfUser
export default function ({ app, redirect, _req }) {
if (app.store.state.user) {
if (app.store.state.user.roles.includes("customer")) {
return redirect({
name: "panel",
params: { username: app.store.state.user.username },
});
} else if (app.store.state.user.roles.includes("admin")) {
return redirect("/admin/dashboard");
} else {
return redirect({
name: "panel",
});
}
} else {
return redirect("/");
}
}
pages/login- login method
async userLogin() {
if (this.form.username !== "" && this.form.password !== "") {
await this.$axios
.post("/api/auth/login", this.form)
.then((response) => {
this.$store.commit("setUser", response.data);
this.$store.commit("setAuthenticated", true);
this.$cookies.set("authUser", JSON.stringify(response.data), {
maxAge: 60 * 60 * 24 * 7,
});
if (this.$route.query.redirect) {
this.$router.push(this.$route.query.redirect);
}
this.$router.push("/panel");
})
.catch((e) => {
this.$toast
.error("Error logging in", { icon: "error" })
.goAway(800);
The cookie is sent by the server but the client won't read it, until you set the property withCredentials in your client request (about withCredentials read here)
To fix your problem you have to extend your auth config with withCredentials property.
endpoints: {
login: {
url: 'http://localhost:8000/api/login2/',
method: 'post'
withCredentials: true
}
}
Also don't forget to set CORS policies on your server as well to support cookie exchange
Example from ExpressJS
app.use(cors({ credentials: true, origin: "http://localhost:8000" }))
More information about this issue on auth-module github

Serverless framework on AWS - Post API gives Internal server error

My serverless.yml looks like this -
service: books-api-v1
provider:
name: aws
region: eu-west-1
role: arn:aws:iam::298945683355:role/lambda-vpc-role
runtime: nodejs8.10
iamRoleStatements:
- Effect: Allow
Action:
- "ec2:CreateNetworkInterface"
- "ec2:DescribeNetworkInterfaces"
- "ec2:DeleteNetworkInterface"
Resource: "*"
functions:
login:
handler: api/controllers/authController.authenticate
vpc: ${self:custom.vpc}
events:
- http:
path: /v1/users/login
method: post
cors: true
And the actual API function looks this -
'use strict';
var db = require('../../config/db'),
crypt = require('../../helper/crypt.js'),
jwt = require('jsonwebtoken');
exports.authenticate = function(event, context, callback) {
console.log(JSON.parse(event.body));
const data = IsJsonString(event.body) ? JSON.parse(event.body) : event.body;
let myEmailBuff = new Buffer(process.env.EMAIL_ENCRYPTION_KEY);
db.users.find({
where:{
username : crypt.encrypt(data.username)
}
}).then(function(user) {
try {
let res = {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message:'ERROR!',
success: false
})
};
if (!user) {
res.body = JSON.stringify({
success: false,
message: 'Authentication failed. User not found.',
authFail:true
});
//res.status(200).json({ success: false, message: 'Authentication failed. User not found.',authFail:true, });
}else if (user) {
// check if password matches
if (crypt.decrypt(user.password) != data.password) {
res.body = JSON.stringify({
success: false,
message: 'Authentication failed. Wrong password.',
authFail:true
});
//res.status(200).json({ success: false, message: 'Authentication failed. Wrong password.',authFail:true, });
} else {
// if user is found and password is right
// create a token with only our given payload
// we don't want to pass in the entire user since that has the password
const payload = {
username: crypt.decrypt(user.username)
};
var token = jwt.sign(payload, process.env.JWT_SIGINING_KEY, {
algorithm: process.env.JWT_ALGORITHM,
expiresIn: 18000,
issuer: process.env.JWT_ISS
});
// return the information including token as JSON
// res.status(200).json({
// success: true,
// message: 'Enjoy your token!',
// token: token
// });
res.body = JSON.stringify({
success: true,
message: 'Enjoy your token!',
token: token
});
}
//callback(null, res);
}
console.log(res);
callback(null, res);
} catch (error) {
console.log('errorsssss: ');
console.log(error);
}
});
};
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Works very well on my serverless local, but when I try it on AWS Lambda function, then it gives "Internal server error" Message.
I have looked into my cloudwatch logs and the response looks correct to me. Here is the response that I am sending back to callback.
{
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true
},
body: '{"success":true,"message":"Enjoy your token!","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNhaW1hLm5hc2lyckBnbWFpbC5jb20iLCJpYXQiOjE1NDUwNjE4OTYsImV4cCI6MTU0NTA3OTg5NiwiaXNzIjoiaWFtbm90YWdlZWsuY28udWsifQ.2HyA-wpmkrmbvrYlWOG41W-ezuLCNQnt0Tvrnsy2n3I"}'
}
Any help please?
In this case, it might because of the Api Gateway configurations. Does your api public? Because I have met such problems when the api is not public.

Why is request.auth.session undefined?

I've created an auth strategy using bell and another using hapi-auth-cookie. However, when I try to set a session request.auth.session is undefined. Can someone help me figure out where I am going wrong?
My route:
module.exports = [
{
method: 'GET',
path: '/create-an-account',
config: {
auth: {
strategy: 'auth0',
mode: 'try'
}
},
handler: function(request, reply) {
var credentials = request.auth.credentials;
request.auth.session.set(credentials);
return reply.view('create-an-account');
}
}
]
My auth strategies:
exports.register = function (server, options, next) {
server.register([Bell, Cookie], function (err) {
server.auth.strategy('auth0', 'bell', {
provider: 'auth0',
config: {
domain: process.env.AUTH0_CLIENT_DOMAIN,
},
password: 'cookie_encryption_password_secure',
clientId: process.env.AUTH0_CLIENT_ID,
clientSecret: process.env.AUTH0_CLIENT_SECRET,
isSecure: false // For developing locally
});
server.auth.strategy('session', 'cookie', {
password: 'cookie_encryption_password_secure',
cookie: 'sid',
redirectTo: '/create-an-account',
redirectOnTry: false,
isSecure: false
});
});
return next();
};
We had this issue a little while ago on one of our projects. Hapi-auth-cookie have changed their documentation so they longer use request.auth.session.set(credentials);
Here's a link to the commit
If you change that line to request.cookieAuth.set() instead it should work. A lot of the examples online seem to use the old example which is how we missed it first time.
This was also picked up in another SO answer here > request.auth.session.set(user_info) not working HapiJS