hapijs / cookie Goto Github PK
View Code? Open in Web Editor NEWCookie authentication plugin
License: Other
Cookie authentication plugin
License: Other
Very new to Hapi here, but it appears to me that the README should have s/server.pack.require/server.pack.register in the code example.
It would be really helpful if you could add an example of storing the session in a database.
Or should I be looking at one of the other packages?
I'm wondering whether it is possible to access the current "request" object from within the "validateFunc" callback function, for instance to check a contained IP address against the IP address of the requesting client? Is there a way I've overlooked? I would have expected that either the "request" object is passed into "validateFunc" as an additional parameter or that the "session" object has a backreference to the "request" object (perhaps directly via "session.request")...
Hi.
the build is broken, can you please fix this ?
How do we remove sessions when the browser session ends?
Or is it bad practice to use that option?
Would it be possible to pass the request object to the validateFunc
method? See my fork for a very trivial/slapdash implementation.
In my use case I'm writing a Hapi server that largely acts as a proxy to a different API. My validateFunc
implementation includes a call out to this backing service to verify the user's auth token. The actual information I'm seeking to validate I'm storing in the session cookie (and thus get back as the first argument in validateFunc
) but there's some other data in the request (like the user's IP address) that I'd like to forward on to the backing API for general logging/tracking purposes.
Is this a reasonable addition? Or is there some best practice I might be missing in my approach?
Needing to host multiple HAPI applications under the same domain, but separated by resource path. Currently the module hardcodes the path to '/', and not having an option to change.
I get No compatible version found: hapi@'>=8.0.0'
when I try to install the latest version. I have hapi v8.0.0-rc4
.
Hi guys,
I encountered a problem.
I have a web app composed of JS front + NodeJS API backend.
I use hapi + auth-cookie for sessions on the backend.
All of the frontend interaction is done with the content through AJAX API calls.
Some of these calls update data that is also present in the session.
For example it changes the user email, user being stored in the session.
I wrote code to refresh the session, but to my amazement it was not working.
After 1 day of thinking it over and over I think it has to do with the fact that all calls were AJAX and therefore the browser was not updating the session cookie.
I changed then the implementation of the hapi-auth-cookie to use a server side cache for storing the session data and in the cookie there is the sessionId.
This way my session gets refreshed correctly.
I am curious if you are interested in making this part of the plugin?
Thanks,
Daniel
What is the right setup two make cross domain work with session on this plugin?
If we create a breaking change and want to clear the auth cookie for a user, how do you recommend doing that?
Hi,
got confused by following docs for validateFunc
credentials - a credentials object passed back to the application in request.auth.credentials. If value is null or undefined, defaults to session. If set, will override the current cookie as if request.auth.session.set() was called.
Because source code suggests that cookie just get updated by session
object, not credentials
object. And it gets updated only if keepAlive
is true.
Replaces #28
Trying to use hapi-auth-cookie with a custom cookie name, validationFunc, and random password on each app restart seems to lead to "Bad cookie value" response anytime the app restarts. I thought clearInvalid would automatically clear the cookie, but it doesn't appear to.
Dirty sample below that shows basically what I'm doing without all the login/logout/etc... for clarity.
server.pack.register(Cookie, function (err){
server.auth.strategy('auth', 'cookie', {
password: config.password||uuid(),
cookie: 'myapp',
redirectTo: false,
validateFunc: validate,
isSecure: config.isSecure||false,
clearInvalid: true
});
server.route([
{
method: 'GET',
path: 'api/v1/test/auth',
handler: function(req, reply){
reply('Ok :)');
},
auth: 'auth'
}
]);
});
Any pointers on where I'm going wrong?
Here is my use case. I'm building new frontend app for our legacy website. Temporarily I need to provide a flow where user logs in through my new app and I set 2 cookies, one for the new app session, and one for the legacy site ( written in PHP ).
Basically I'm trying to find a way how to set new session cookie ( or a cookie with custom name and value and not protected by Iron ) so our legacy app could read it, in addition to standard session cookie provided by hapi-auth-cookie.
Maybe it's not 100% related to this plugin, but I hope you can point me to the right direction...
My code pretty much looks very similar to this repo.
https://github.com/santbob/hapi-auth-example
my request.auth object is
{ account:
{ provider: 'instagram',
token: ' ',
query: {},
profile:
{ id: ' ',
username: ' ',
displayName: ' ',
raw: [Object] } } }
{ isAuthenticated: true,
credentials:
{ provider: 'instagram',
token: ' ',
query: {},
profile:
{ id: ' ',
username: ' ',
displayName: ' ',
raw: [Object] } },
artifacts: { sid: ' ' },
session: { set: [Function], clear: [Function], ttl: [Function] },
mode: 'try',
strategy: 'session' }
In one of my handlers, I tried
if (request.auth.isAuthenticated)
and it did not pass.
How/where do I access the cookie so I can check if a user is authenticated in other parts of my app?
I've verified with Hapi 6.2 that when I return new credentials from validateFunc they do not update the session credentials.
peerDependencies and devDependencies for hapi still point to 2.x.x and need to be updated to 3.x.x
Currently, it is not possible to configure some of the options in this plugin using environment variables, since some of the options are assumed to be boolean/number types, while environment variables are strings.
I would like to request that this be made possible by using Joi's nifty validation() function which will accept a boolean/number string and return a transformed object with the appropriate types.
Pull request incoming.
After not having started my server for a few hours, I receive the following error when I attempt to access a page with try
as the mode: {"statusCode":400,"error":"Bad Request","message":"Invalid cookie value"}
I've looked at #34 which seems to say this is fixed/intended (not really sure which), however I do have "clearInvalid" set in my initialization, and the cookie password does not change.
# declare max valid time for session
sessionTime = 3 * 24 * 60 * 60 * 1000
# setup session cache
cache = server.cache({ cache:'sessionCache',segment: 'auth', expiresIn: sessionTime })
# Setup cookie based session authentication
server.register require("hapi-auth-cookie"), (err) ->
if err?
throw err
server.auth.strategy 'session', 'cookie', true,
password: 'eetsacookies'
ttl: sessionTime
keepAlive: true
cookie: 'sid'
redirectTo: "/login"
redirectOnTry: false
clearInvalid: true
isSecure: process.env.NODE_ENV isnt "development"
validateFunc: (session, callback) ->
cache.get session.sid, (err, cached) ->
if err?
return callback(err, false)
else if not cached?
return callback(null, false)
else
Information.User.findById cached.userId, (err,user) ->
if err?
return callback( err,false)
else
return callback( null, true, user)
Any idea how I can have this error not appear? Is there a bug in my implementation or is this something with the library/hapi? Thanks in advance.
I'm wondering how to use this so that on every request it will set my current authenticated user. Currently it seems that the only time request.auth.isAuthenticated
is set is when I specifically set the route to require authentication. I'm trying to figure out how to get functionality like in rails or other frameworks where you always have access to the request.auth
record without having to force them to be authenticated on each route. That way I can set a navbar header with the current logged in user on all pages. Does this make sense? Is there some other plugin I should be using for this?
Hello,
I am using socket.io to get username and password from user and after validating username and password I want to set session for him.
I want auth to be optional, and simply return a slightly different page whether you have a session or not.
It seems like i should be able to set auth.mode
to try
and redirectOnTry = false
and reply without passing the error through.
The unauthenticated error gets created here: https://github.com/spumko/hapi-auth-cookie/blob/master/lib/index.js#L81
Then included here: https://github.com/spumko/hapi-auth-cookie/blob/master/lib/index.js#L109
It replies properly but that exception shows up in logs even though it's not an exception .
Seems like maybe it shouldn't? Or am I doing it wrong.
I basically want optional auth without errors in either case.
Hi,
I've encountered a strange bug. I used the sample code passport 'worldofwalmart', now I'm trying to change it, but I'm constantly getting 400 "Bad cookie value: session". It doesn't matter which password I use. It only works 'worldofwalmart'.
My code:
yield server.pack.register require('hapi-auth-cookie')
server.auth.strategy 'session', 'cookie',
password: 'worldofwalmart'
cookie: 'session'
redirectTo: false
isSecure: true
ttl: 24* 60 * 60 * 1000
Working fine.
yield server.pack.register require('hapi-auth-cookie')
server.auth.strategy 'session', 'cookie',
password: <anything but 'worldofwalmart'>
cookie: 'session'
redirectTo: false
isSecure: true
ttl: 24* 60 * 60 * 1000
400 "Bad cookie value: session"
Do I have to clear some kind of cache or something?
I have a thorax client app that is hosted on a static server. It needs to be accessible from various subdomains (foo.example.com, bar.example.com, baz.example.com). Each of the subdomains loads the same static files/thorax app.
I have a hapi.js app running on api.example.com with auth-cookie scheme in place.
My issue is having foo.example.com perform a login request and having api.example.com set the cookie for the session to be recognized on the server side in following request to protected endpoints.
If I make the request from foo.example.com to foo.example.com/login the cookie is set and the session works. However, this is not suitable for production. We need to have a static server serve up the thorax app and the hapi server manage sessions and endpoints.
I have CORS setup as such:
cors: {
matchOrigin: true,
isOriginExposed: false,
headers: ['Authorization', 'Content-Type', 'If-None-Match'],
maxAge: Math.round(86400 * (365/12)),
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
},
Any advice or help would be great appreciated!
Thanks.
Hapi's server.state accepts domain: null
as an option, and this is a useful setting for me when in active development, because devs all use different local domains.
I think schema validation should be updated, and the logic here adapted to check property presence, not truthiness:
if (settings.hasOwnProperty('domain')) {
cookieOptions.domain = settings.domain;
}
We have a default hapi-auth-cookie expiration of 2 weeks. However, for some users we want to allow them to set the auth cookie to be browser session only (e.g. unchecking a remember me
checkbox on the login form).
e.g. plugin config
options: {
password: process.env.AUTH_COOKIE_PWD,
ttl: moment.duration(2, 'weeks').asMilliseconds(),
domain: process.env.AUTH_COOKIE_DOMAIN,
redirectUrl: '/login'
}
During the request we have something like this:
if(!remember) {
request.auth.session.ttl(null);
}
However, this will still result in the ttl being set to moment.duration(2, 'weeks').asMilliseconds(),
. It looks like statehood
will always take the base options when the ttl is set to null: var definition = cookie.options ? Hoek.applyToDefaults(base, cookie.options) : base;
(https://github.com/hapijs/statehood/blob/4fdaea4677c147e61175ad7ded4fa54dd1125dd7/lib/index.js#L354)
This makes sense from the statehood
perspective, but from the hapi-auth-cookie
perspective my expectation as a user would be that calling request.auth.session.ttl()
would override the ttl set in default options - this only appears to be the case some of the time (for non-null values)
We can work around this on our side by defaulting everything to browser session and inverting our logic to explicitly set the ttl using this following:
if(remember === true) {
request.auth.session.ttl(moment.duration(2, 'weeks').asMilliseconds());
}
However, this now means our main-line scenario (people leaving the box checked) has it's ttl separated from the hapi-auth-cookie plugin config.
Wanted to open this issue to see if there is a solution to have request.auth.session.ttl(null);
work or if the hapi-auth-cookie
docs should be updated to point out this scenario.
I'm trying to figure out how I can redirect a user to /login?next=/protected
only when authentication is required on a route.
For example, /
should be public & accessible to anybody.
But when going to /protected
& not logged in, you should be redirected to the route above.
I tried implementing this myself with onPreAuth
but as I can't detect if a user is authenticated yet, it's not possible there. onPostAuth
doesn't work either, as it has already redirected the request if it's not authenticated.
I would like to understand how to access auth to an end point even though its not required that one would have been authenticated, in a way, offer a different views according to authenticated users.
Simple example, /register
if one is authenticated skip, if not show the form. My problem is if i use auth: 'stategy'
, everyone get redirected to /redirectURI
with next register
which is not what i want.
Just need to add attributes
. For full migration to v6.0 look at the hapi6 branch (not ready for integration as hapi v6.0 has not been published, but adding attributes
now is safe).
Received this error:
/Users/rockbot/npm-inc/newww/node_modules/hoek/lib/index.js:669
throw arguments[1];
^
ValidationError: child "appendNext" fails because ["appendNext" must be a boolean]
at Object.exports.process (/Users/rockbot/npm-inc/newww/node_modules/hapi-auth-cookie/node_modules/joi/lib/errors.js:140:17)
at internals.Any._validateWithOptions (/Users/rockbot/npm-inc/newww/node_modules/hapi-auth-cookie/node_modules/joi/lib/any.js:642:25)
at root.validate (/Users/rockbot/npm-inc/newww/node_modules/hapi-auth-cookie/node_modules/joi/lib/index.js:102:23)
at Object.internals.implementation [as cookie] (/Users/rockbot/npm-inc/newww/node_modules/hapi-auth-cookie/lib/index.js:41:23)
at internals.Auth.strategy (/Users/rockbot/npm-inc/newww/node_modules/hapi/lib/auth.js:47:41)
at internals.Plugin._applyChild (/Users/rockbot/npm-inc/newww/node_modules/hapi/lib/plugin.js:449:19)
at Object.auth.strategy (/Users/rockbot/npm-inc/newww/node_modules/hapi/lib/plugin.js:61:65)
at /Users/rockbot/npm-inc/newww/server.js:90:15
at done (/Users/rockbot/npm-inc/newww/node_modules/hapi/node_modules/items/lib/index.js:30:25)
at Object.exports.register (/Users/rockbot/npm-inc/newww/node_modules/hapi-auth-cookie/lib/index.js:15:5)
at /Users/rockbot/npm-inc/newww/node_modules/hapi/lib/plugin.js:242:14
at iterate (/Users/rockbot/npm-inc/newww/node_modules/hapi/node_modules/items/lib/index.js:35:13)
at Object.exports.serial (/Users/rockbot/npm-inc/newww/node_modules/hapi/node_modules/items/lib/index.js:38:9)
at internals.Plugin.register (/Users/rockbot/npm-inc/newww/node_modules/hapi/lib/plugin.js:224:11)
at Object.<anonymous> (/Users/rockbot/npm-inc/newww/server.js:80:8)
at Module._compile (module.js:456:26)
Here's the code that we've written (worked fine with version 2.0.0):
server.auth.strategy('session', 'cookie', 'required', {
password: process.env.SESSION_PASSWORD,
appendNext: 'done',
redirectTo: '/login',
cookie: process.env.SESSION_COOKIE,
clearInvalid: true,
validateFunc: function (session, cb) {
cache.get(session.sid, function (err, item, cached) {
if (err) {
return cb(err, false);
}
if (!cached) {
return cb(null, false);
}
return cb(null, true, item);
});
}
});
Sidenote: if this was a purposeful, breaking change, the community would expect the version to be bumped to 3.0.0, not 2.1.0.
Is there a way to update one key or add an additional key to auth.credentials
without calling auth.session.set
with a new object?
Something similar to flash(type, message, isOverride) in Yar ? I think it's pretty common for websites to have the option to display some kind of one time messages 'error', 'success', 'warning' and it seem to have this wrapper method in the plugin for convenient use in request handlers. Or maybe there is better way to store one time sitewide messages?
So, my case:
If you access directly to an url which needs some auth and your aren't logged. I cannot get the refer url because I've been redirected. For example:
A. Access to domain.com/private
B. Because isn't logged it's redirected to domain.com/auth/signin
C. In the handlers now there's the data of /auth/signin not /private
I hope I've explained myself well enough. Maybe I'm thinking in a bad way and I shouldn't check the refer url like that, but this will be possible using Hapi? Or is planned? Or something?
Thanks
I think this is more of a question than an issue. In my login page I'd like to perform the login, set the credentials and then display the user's authenticated dashboard without redirecting to the dashboard url. It looks like when I call reply.view with the request.auth.credentials after calling request.auth.session.set it is undefined. Is this because the credentials are set earlier in the pipeline and calling set doesn't update until the next request?
IE:
// do login stuff and get a user object that we want to save in session
request.auth.session.set(user);
reply.view('dashboard', { user: request.auth.credentials });
redirectTo
has effectively been required, though logic still exists handling it as undefined / false.
Was this an oversight? I was handling redirect differently in my app, in a way that necessitated bypassing the hapi-auth-cookie redirect action.
These dev browsers (FX 39 and Chrome 43) appear to be unable (or unwilling?) to set a session cookie generated by hapi-auth-cookie.
Here's my reduced test case: https://gist.github.com/cadecairos/5bcfa6aeba06c2c69952
I'm actually using Bell and hapi-auth-cookie and I'm not sure which (or both) plugins would need to be involved since I don't quite understand yet how they interact, but I need to be able to send someone to a route to initiate auth and after they're successfully authenticated, redirect them to that URL.
It seems like this is a standard part of the OAUTH process, or at least once was, but I'm wondering if these plugins use that functionality and thus need to provide it themselves to effectively bring it back.
I'm trying to build a plugin to ease the use of bell and hapi-auth-cookie hapi-bell-cookie-auth-plugin, but just today I found another doing something similar https://github.com/hofan41/clapper and even more nicely written (though mine is very fresh in my defense).
I'm going to post this in Bell also and will close on either side if/when it's clear that it's a one-sided issue.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.