29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

}<br />

}<br />

public void<br />

OnAuthenticationChallenge(AuthenticationChallengeContext context) {<br />

if (context.Result == null || context.Result is<br />

HttpUnauthorizedResult) {<br />

context.Result = new RedirectToRouteResult(new<br />

RouteValueDictionary {<br />

{"controller", "GoogleAccount"},<br />

{"action", "Login"},<br />

{"returnUrl", context.HttpContext.Request.RawUrl}<br />

});<br />

}<br />

}<br />

}<br />

}<br />

My implementation of the OnAuthentication method checks to see if the request has been authenticated using a<br />

username that ends with @google.com. If the request is not authenticated or the request is authenticated using a different<br />

kind of credential, then I set the Result property of the AuthenticationContext object to a new<br />

HttpUnauthorizedResult.<br />

The HttpUnauthorizedResult is set as the Result value for the<br />

AuthenticationChallengeContext object that is passed to the OnAuthenticationChallenge<br />

method and you can see that I have updated this method to challenge the user when this happens, coordinating the actions of the<br />

two methods in the filter. The next step is to apply the filter to the controller, which you can see in Listing 18-17.<br />

Listing 18-17. Applying the Authentication Filter in the HomeController.cs File<br />

using System.Web.Mvc;<br />

using Filters.Infrastructure;<br />

namespace Filters.Controllers {<br />

public class HomeController : Controller {<br />

[Authorize(Users = "admin")]<br />

public string Index() {<br />

return "This is the Index action on the Home controller";<br />

}<br />

}<br />

}<br />

[GoogleAuth]<br />

public string List() {<br />

return "This is the List action on the Home controller";<br />

}<br />

I have defined a new action method called List, which I decorated with the GoogleAuth filter. The result is that access<br />

to the Index method is secured through the built-in support for forms authentication but that access to the List action<br />

method is secured through my custom fake Google authentication system.<br />

You can see the effect by starting the application. By default the browser will target the Index action method, which will<br />

trigger the standard authentication and require you to log in using one of the usernames that I defined in the Web.config file.<br />

If you then request the /Home/List URL, then your existing credentials will be rejected and you will have to authenticate<br />

using a Google username.<br />

472

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

Saved successfully!

Ooh no, something went wrong!