Skip to content

brief overview of the form authentication example

superafroman edited this page Nov 18, 2010 · 1 revision

Brief overview of the form authentication example

The form authentication example can be found here.

What does it do?

The example app is very simple. It has three pages that you can view,

The application also maps /logout which simply redirects the user to the homepage (though connect-security also hooks in to this).

The main bit - the middleware chain.

  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

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

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.

Secure a page

  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.

Logout

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!