-
Notifications
You must be signed in to change notification settings - Fork 2
brief overview of the form authentication example
The form authentication example can be found here.
The example app is very simple. It has three pages that you can view,
- A un-secure homepage (http://127.0.0.1/)
- A login page (http://127.0.0.1/login)
- A secure page (http://127.0.0.1/secure)
The application also maps /logout which simply redirects the user to the homepage (though connect-security also hooks in to this).
var server = connect.createServer(
connect.cookieDecoder(),
connect.bodyDecoder(),
connect.session(),
security.formAuthenticationChain({
rememberMe:{},
userProvider: new InMemoryUserProvider({users:
{'test': {username:'test', password: '12345', roles: ['user']}}
})
}),
connect.router(urls),
security.errorHandler()
);
connect-security makes use of sessions, to keep track of user logged in/out state and cookies, for remember me and tracking the session. So both the cookieDecoder middleware and session middleware need to be in the chain before the connect-security middleware.
security.formAuthenticationChain is a helper method for setting up a default form authentication chain. Essentially it puts together a chain including a RememberMeAuthenticationFilter (if 'rememberMe' is defined in the config) and a FormAuthenticationFilter with a FormAuthenticationEntryPoint.
security.errorHandler is needed to deal with any SecurityErrors that are thrown while handling the request. If a SecurityError is thrown and no user is authenticated then the configured entry point is used to commence authentication. In the case of the FormAuthenticationEntryPoint the user is redirected to the configured login URL (by default /login). If a SecurityError is thrown and a user is authenticated the a 403 will be raised.
app.get('/secure', function(req, res, next) {
security.secure('user', req, function() {
...
});
)};
The function security.secure(...) restricts access to the callback by checking if there is a logged in user and if they have any of the roles specified (in the above case only user). If there is no logged in user, or they don't have an appropriate role a SecurityError is raised and the authentication process will kick off.
The example application maps /logout to a function that redirects the user to the homepage. However this URL is also mapped, by default, to the LogoutFilter which logs the user out!