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
Related
I'm using Ember CLI Storybook to create a story of a component than internally relies upon services that communicate to the internet, to fetch and post information to the backend. The way I'm doing that is using ember-ajax.
I see how to mock an ember model from this section but wondering if there is a workaround for ember ajax service.
I like to use mswjs.io for mocking remote requests. It uses a service worker so you can still use your network log as if you still used your real API.
I have an example repo here showing how to set it up: https://github.com/NullVoxPopuli/ember-data-resources/
But I'll copy the code, in case I change something.
Now, in tests, you'd want something like this: https://github.com/NullVoxPopuli/ember-data-resources/blob/main/tests/unit/find-record-test.ts#L17
module('findRecord', function (hooks) {
setupMockData(hooks);
But since you're using storybook, you'd instead want the contents of that function. (And without the setup/teardown hooks unique to tests)
https://github.com/NullVoxPopuli/ember-data-resources/blob/main/tests/unit/-mock-data.ts#L22
import { rest, setupWorker } from 'msw';
let worker;
export async function setupMockData() {
if (!worker) {
worker = setupWorker();
await worker.start();
// artificial timeout "just in case" worker takes a bit to boot
await new Promise((resolve) => setTimeout(resolve, 1000));
worker.printHandlers();
}
let data = [
{ id: '1', type: 'blogs', attributes: { name: `name:1` } },
{ id: '2', type: 'blogs', attributes: { name: `name:2` } },
{ id: '3', type: 'blogs', attributes: { name: `name:3` } },
];
worker.use(
rest.get('/blogs', (req, res, ctx) => {
let id = req.url.searchParams.get('q[id]');
if (id) {
let record = data.find((datum) => datum.id === id);
return res(ctx.json({ data: record }));
}
return res(ctx.json({ data }));
}),
rest.get('/blogs/:id', (req, res, ctx) => {
let { id } = req.params;
let record = data.find((datum) => datum.id === id);
if (record) {
return res(ctx.json({ data: record }));
}
return res(
ctx.status(404),
ctx.json({ errors: [{ status: '404', detail: 'Blog not found' }] })
);
})
);
}
Docs for msw: https://mswjs.io/
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
I am using crypto and oauth-1.0a from nmp in ionic2 application. I want to access WP-API which is correctly set to handle authentication, I tested this using Postman.
Http.Get results in the following error:
{
"_body": {
"isTrusted": true
},
"status": 0,
"ok": false,
"statusText": "",
"headers": {},
"type": 3,
"url": null
}
The options generated that I pass as argument to Http.Get are as follows:
{“method”:0,“headers”:{“Authorization”:“OAuth oauth_consumer_key=”",
oauth_nonce=“jSZGPwkj4quRGMb0bhBLYKwmc3BGfrQw”, oauth_signature=“x3zseS3XTFBLMsNDLXC4byn2UDI%3D”,
oauth_signature_method=“HMAC-SHA1”, oauth_timestamp=“1522414816”,
oauth_token="",
oauth_version=“1.0"”},“body”:null,“url”:"",“params”:{“rawParams”:"",“queryEncoder”:{},“paramsMap”:{}},“withCredentials”:null,“responseType”:null}
Part of code:
this.oauth = new OAuth({
consumer: {
key: this.apiconstant.consumerkey,
secret: this.apiconstant.consumersecret
},
signature_method: ‘HMAC-SHA1’,
hash_function: hash_function_sha1,
realm:’’
});
let request_data = {
url: ‘’,
method: ‘GET’
};
let token={
key: this.apiconstant.token,
secret: this.apiconstant.tokensecret
}
//This part doesn’t seem to work
this.authkey = this.oauth.authorize(request_data,token);
this.keyoauth = new URLSearchParams();
for (let param in this.authkey) {
this.keyoauth.set(param, this.authkey[param]);
}
let options = new RequestOptions({
method: ‘GET’,//request_data.method
url: ‘’,
headers: this.oauth.toHeader(this.oauth.authorize(request_data,token)),
search: this.keyoauth
});
this.http.get(’’,options)
.map(res => res.json()).subscribe(data=>{
console.log(‘Resulting data’ + JSON.stringify(data));
},
error=>{
console.log(‘Got error’+JSON.stringify(error));
});
//Error part executed
What am I missing here? I’m testing my app on android device. Without authentication I get desired results from the WP-API (Wordpress), that is if the Oauth is disabled on WP-API.
Please help! This is my second day on this. I should also let you know I’m new on these technologies but I’m able to research and understand how they work.
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);
I am trying to add a non-static remote method to a model. Just follow the code here. Unfortunately, I got some error message.
The following is my code
User.prototype.lastOrder = function(callback){
console.log('print this instance object: ', this);
callback(null)
};
User.remoteMethod('__get__lastOrder', {
isStatic: false,
accepts: [],
description: 'Get the latest order of the user',
http: {
path: '/lastOrder',
verb: 'get'
}
And when I invoke http://localhost:3000/v1/users/1/lastOrder. it gives me the following error:
The first argument to remoteMethod is the function name. What you have defined isn't valid. You need to define a function called, well, let's say lastOrder, and then modify your code like so:
User.prototype.lastOrder = function() {
}
User.remoteMethod('lastOrder', {
isStatic:false,
//more stuff here
}
User.prototype.lastOrder = function(callback){
console.log('print this instance object: ', this);
callback(null, "this is a test");
};
User.remoteMethod('lastOrder', { // should be lastOrder not __get__lastOrder
isStatic: false,
accepts: [],
description: 'Get the latest order of the user',
http: {
path: '/lastOrder',
verb: 'get',
status: 200
},
returns: {root: true, type: 'order'}
});