Home >Backend Development >C#.Net Tutorial >asp.net mvc 5 improves filter based authentication

asp.net mvc 5 improves filter based authentication

伊谢尔伦
伊谢尔伦Original
2016-11-24 13:22:001601browse

 ASP.NET MVC 5, included in the recently released Visual Studio 2013 Developer Preview, enables developers to apply authentication filters, which provide the ability to use a variety of third-party vendors or custom authentication providers. The ability to authenticate users. However, these filters are applied before calling the authorization filter.

 In order to create an authentication filter, developers need to create a new C# ASP.NET project and select MVC from the listed project types. Eric Vogel, senior software development engineer at Kunz, Leigh & Associates, has tested the use of authentication filters. He created a custom filter that redirected users back to the login page if they were not authenticated.

Eric created a CustomAttributes directory and a new class CustomAttribute that inherits

ActionFilterAttribute和IAuthenticationFilter:
public class BasicAuthAttribute: ActionFilterAttribute,IAuthenticationFilter

The OnAuthentication() method of the interface IAuthenticationFilter can be used to perform any required authentication, while the OnAuthenticationChallenge method restricts access to the authenticated user based on his/her 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();
    }
}

Readers can get the complete 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, apply the custom attribute to the HomeController class as follows:

[BasicAuthAttribute]
   public class HomeController : Controller


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Future plans for C#Next article:Future plans for C#