Basic HTTP Authentication Interceptor
Introduction
In this recipe we will create a simple interceptor that will be in charge of challenging users with HTTP Basic Authentication. It features the usage of all the new RESTful methods in our Request Context that will make this interceptor really straightforward. We will start by knowing that this interceptor will need a security service to verify security, so we will also touch on this.
Application Setup
Let's start building the app using CommandBox and installing all the necessary dependencies:
Use cbtemplate-advanced-script@6.0.0-snapshot
if using ColdBox Pre-Releases
Security Service
Let's build a simple security service to track users. Use CommandBox to generate the service model with two functions and let's mark it as a singleton:
This will create the models/SecurityService
and the companion unit tests. Let's fill them out:
Security Service Test
Security Service
Please note that we are using a hard coded username and password, but you can connect this to any provider or db.
The Interceptor
Let's generate the interceptor now and listen to preProcess
The preProcess
listener is to listen to all incoming requests are inspected for security. Please note that the unit test for this interceptor is also generated. Let's fill out the interceptor test first:
Interceptor Test
So to make sure this works, here is our Interceptor Test Case with all possibilities for our Security Interceptor.
As you can see from our A,B, anc C tests that we use MockBox to mock the security service, the request context and methods so we can build our interceptor without knowledge of other parts.
Interceptor Code
As you can see it relies on a SecurityService
model object that is being wired via:
Then we check if a user is logged in or not and if not we either verify their incoming HTTP basic credentials or if none, we challenge them by setting up some cool headers and bypass event execution:
The renderData()
is essential in not only setting the 401 status codes but also concatenating to a noExecution()
method so it bypasses any event as we want to secure them.
Interceptor Declaration
Open your Coldbox.cfc
configuration file and add it.
Now reinit your app coldbox reinit
and you are simple auth secured!
Why provider
You might have noticed the injection of the security service into the interceptor used a provider:
DSL prefix, why? Well, global interceptors are created first, then modules are loaded, so if we don't use a provider
to delay the injection, then the storages module might not be loaded yet.
Extra Credit
Now that the hard part is done, we encourage you to try and build the integration test for the application now. Please note that most likely you would NOT do the unit test for the interceptor if you do the integration portion in BDD Style.
Last updated