Building a simple 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.
The Interceptor
Our simple security interceptor will be intercepting at preProcess so all incoming requests are inspected for security. Remember that I will also be putting best practices in place and will be creating some unit tests and mocking for all classes. So check out our interceptor:
/*** Intercepts with HTTP Basic Authentication*/component {// Security Service property name="securityService" inject="id:SecurityService";voidfunctionconfigure(){ }voidfunctionpreProcess(event,struct interceptData){// Verify Incoming Headers to see if we are authorizing already or we are already Authorizedif( !securityService.isLoggedIn() ORlen( event.getHTTPHeader("Authorization","") ) ){// Verify incoming authorizationvar credentials =event.getHTTPBasicCredentials();if( securityService.authorize(credentials.username,credentials.password) ){// we are secured woot woot!return; };// Not secure! event.setHTTPHeader(name="WWW-Authenticate",value="basic realm=""Please enter your username and password for our Cool App!""");
// secured content data and skip event execution event.renderData(data="<h1>Unathorized Access<p>Content Requires Authentication</p>",statusCode="401",statusText="Unauthorized")
.noExecution(); } }}
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:
// Verify Incoming Headers to see if we are authorizing already or we are already Authorizedif( !securityService.isLoggedIn() ORlen( event.getHTTPHeader("Authorization","") ) ){// Verify incoming authorizationvar credentials =event.getHTTPBasicCredentials();if( securityService.authorize(credentials.username,credentials.password) ){// we are secured woot woot!return; };// Not secure! event.setHTTPHeader(name="WWW-Authenticate",value="basic realm=""Please enter your username and password for our Cool App!""");
// secured content data and skip event execution event.renderData(data="<h1>Unathorized Access<p>Content Requires Authentication</p>",statusCode="401",statusText="Unauthorized")
.noExecution();}
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 Test
So to make sure this works, here is our Interceptor Test Case with all possibilities for our Security Interceptor.
component extends="coldbox.system.testing.BaseInterceptorTest" interceptor="simpleMVC.interceptors.SimpleSecurity"{functionsetup(){super.setup();// mock security service mockSecurityService =getMockBox().createEmptyMock("simpleMVC.model.SecurityService");// inject mock into interceptorinterceptor.$property("securityService","variables",mockSecurityService); }functiontestPreProcess(){var mockEvent =getMockRequestContext();// TEST A// test already logged in and mock authorize so we can see if it was calledmockSecurityService.$("isLoggedIn",true).$("authorize",false);// call interceptorinterceptor.preProcess(mockEvent,{});// verify nothing calledassertTrue( mockSecurityService.$never("authorize") );// TEST B// test NOT logged in and NO credentials, so just challengemockSecurityService.$("isLoggedIn",false).$("authorize",false);// mock incoming headers and no auth credentialsmockEvent.$("getHTTPHeader").$args("Authorization").$results("").$("getHTTPBasicCredentials",{username="",password=""}).$("setHTTPHeader");// call interceptorinterceptor.preProcess(mockEvent,{});// verify authorize called onceassertTrue( mockSecurityService.$once("authorize") );// Assert Set HeaderAssertTrue( mockEvent.$once("setHTTPHeader") );// assert renderdataassertEquals( "401",mockEvent.getRenderData().statusCode );// TEST C// Test NOT logged in With basic credentials that are validmockSecurityService.$("isLoggedIn",false).$("authorize",true);// reset mocks for testingmockEvent.$("getHTTPBasicCredentials",{username="luis",password="luis"}).$("setHTTPHeader");// call interceptorinterceptor.preProcess(mockEvent,{});// Assert header never called.AssertTrue( mockEvent.$never("setHTTPHeader") ); }}
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.
Security Service
Now that we have our interceptor built and fully tested, let's build the security service.
component accessors="true" singleton{// Dependencies property name="sessionStorage" inject="coldbox:plugin:SessionStorage";/** * Constructor */ public SecurityService functioninit(){variables.username ="luis";variables.password ="coldbox";returnthis; }/** * Authorize with basic auth */functionauthorize(username,password){// Validate Credentials, we can do better hereif( variables.username eq username ANDvariables.password eq password ){// Set simple validationsessionStorage.setVar("userAuthorized",true );returntrue; }returnfalse; }/** * Checks if user already logged in or not. */functionisLoggedIn(){if( sessionStorage.getVar("userAuthorized","false") ){returntrue; }returnfalse; }}
We use a simple auth with luis and coldbox as the password. Of course, you would get fancy and store these in a database and have a nice object model around it. For this purposes was having a simple 1 time username and password. We also use the SessionStorage plugin in order to interact with the session scope with extra pizass and the most important thing: We can mock it!
Security Service Test
component extends="coldbox.system.testing.BaseModelTest" model="simpleMVC.model.SecurityService"{functionsetup(){super.setup();// init modelmodel.init();// mock dependency mockSession =getMockBox().createEmptyMock("coldbox.system.plugins.SessionStorage");model.$property("sessionStorage","variables",mockSession); }functiontestauthorize(){// A: InvalidmockSession.$("setVar"); r =model.authorize("invalid","invalid");assertFalse( r );assertTrue( mockSession.$never("setVar") );// B: ValidmockSession.$("setVar"); r =model.authorize("luis","coldbox");assertTrue( r );assertTrue( mockSession.$once("setVar") ); }functiontestIsLoggedIn(){// A: InvalidmockSession.$("getVar",false);assertFalse( model.isLoggedIn() );// B: ValidmockSession.$("getVar",true);assertTrue( model.isLoggedIn() ); }}
Again, you can see that now we use our BaseModelTest case and continue to use mocks for our dependencies.
Interceptor Declaration
Open your Coldbox.cfc configuration file and add it.
//Register interceptors as an array, we need orderinterceptors = [//SES {class="coldbox.system.interceptors.SES"},// Security { class="interceptors.SimpleSecurity" }];
We just add our Simple Security interceptor and reinit your application and you should be now using simple security.