deitch / cansecurity

nodejs/expressjs authentication and security library
MIT License
150 stars 53 forks source link

Init function should have option to redirect on authentication failure #20

Open ProgramCpp opened 7 years ago

ProgramCpp commented 7 years ago

Init function should have option to redirect on authentication failure with status 302 Found.

Redirect to login page is desirable in the following cases.

deitch commented 7 years ago

302 makes sense primarily in the context of a Web UI. Normally REST API calls do not invoke a 302 but a 401, potentially with a Location header (I was dealing with precisely this issue over the last 2 weeks with a client).

So what we would need is:

  1. A definition of the default response - currently 401, overridable to 302 on a global basis
  2. A per-route override, like below (without which it would use the global default):
// for UI
app.get("/secure/loggedin",cansec.unauthorized(302),cansec.restrictToLoggedIn,send200);
// for API - returns 401 because that is the default
app.get("/api/secure/loggedin",cansec.restrictToLoggedIn,send200);

If you want to set the default otherwise:

cansec.init({... , unauthenticatedCode: 302, ...});
// for UI - returns 302 because that was set in this case as the primary
app.get("/secure/loggedin",cansec.restrictToLoggedIn,send200);
// for API
app.get("/api/secure/loggedin",cansec.unauthorized(401),cansec.restrictToLoggedIn,send200);

Open to a PR when you are ready.

ProgramCpp commented 7 years ago

What would be the route entry in the config file? What about the location header for 302?

deitch commented 7 years ago

What about the location header for 302?

Good point, so you would need to extend the init() to include that. Maybe more like:

cansec.init({... , unauthenticated: {code: 302, location: ...}, ...});