ASP. NET MVC 5 is included in the recently released Visual Studio 2013 Developer Preview, which enables developers to apply authentication filters that provide the ability to authenticate users using a variety of third-party vendors or custom authentication providers. However, these filters are to be applied before the authorization filter is invoked.
In order to create an authentication filter, the developer needs a new c#asp. NET project, and choose MVC from the list of project types. Eric Vogel, senior software Development engineer from Kunz,leigh&associates, has tested the use of authentication filters. He creates a custom filter that redirects back to the login page if the user is not authenticated.
Eric creates a customattributes directory and a new class Customeattribute that inherits the
ActionFilterAttribute and Iauthenticationfilter:public class Basicauthattribute:actionfilterattribute, Iauthenticationfilter
The OnAuthentication () method of the interface Iauthenticationfilter can be used to perform any required authentication, and the Onauthenticationchallenge method restricts its access based on the authenticated user's identity.
The Onauthenticationchallenge method receives the Authenticationchallengecontext parameter, and its implementation code is as follows:
public void Onauthenticationchallenge (Authenticationchallengecontext filtercontext) { var user = FilterContext.HttpContext.User; if (user = = NULL | |!user. identity.isauthenticated) { Filtercontext.result = new Httpunauthorizedresult ();} }
The reader can get the full source code from Eric's blog post. The Basicauthattribute class is easy to test, open the HomeController class file, and add the following code:
Using Vsmmvc5authfilterdemo.customattributes;
Finally, you apply the custom attribute to the HomeController class as follows:
[Basicauthattribute] public class Homecontroller:controller