29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Figure 12-1. The effect of the Authorize filter<br />

When you try to access the Index action method of the Admin controller, the MVC Framework detects the<br />

Authorize filter. Because you have not been authenticated, you are redirected to the URL specified in the Web.config<br />

forms authentication section: /Account/Login. I have not created the Account controller yet (which is what causes<br />

the error shown in the figure), but the fact that the MVC Framework has tried to redirect the request shows that the<br />

Authorize filter is working.<br />

Creating the Authentication Provider<br />

Using the forms authentication feature requires calls to two static methods of the<br />

System.Web.Security.FormsAuthentication class:<br />

The Authenticate method validates credentials supplied by the user.<br />

The SetAuthCookie method adds a cookie to the response to the browser, so that users do not need to authenticate<br />

every time they make a request.<br />

The problem with calling static methods from within action methods is that it makes unit testing the controller difficult: mocking<br />

frameworks typically mock only instance members. The classes that comprise the MVC Framework have been designed with unit<br />

testing in mind, but the FormsAuthentication class predates the unit testing-friendly design of MVC.<br />

The best way to address the problem is to decouple the controller from the static methods using an interface, which offers the<br />

additional benefit that this fits in with the broader MVC design pattern and makes it easier to switch to a different authentication<br />

system later.<br />

I start by defining the authentication provider interface. Create a new folder called Abstract in the Infrastructure<br />

folder of the SportsStore.WebUI project and add a new interface called IAuthProvider. The contents of this<br />

interface are shown in Listing 12-4.<br />

304

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!