ASP. NET MVC 5 improves filter-based authentication

Source: Internet
Author: User
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
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.