ASP. NET MVC authentication, exception handling, permission validation (interceptor) Implementation code

Source: Internet
Author: User
Tags decrypt httpcontext ticket

This question mainly introduces the authentication mechanism of ASP and the application of ASP. Now let's simulate a simple process: User Login "Permission Validation" exception handling

1. User Login
To verify that the user is logged on successfully, and how to save the current user login information (session,cookie) after the user has successfully logged in, this article describes the authentication (in fact, cookie-based), and look at the code below.
Introducing namespaces
Using System.Web.Security;

Users Modeluser =NewUsers () {ID =10000, Name = UserName, UserName = UserName, PassWord = PassWord, Roles ="Admin"};//User EntitiesstringUserData = serializehelper.instance.jsonserialize<users> (Modeluser);//Serializing User Entities//Save identity information, parameter description can be seen promptFormsAuthenticationTicket Ticket =NewFormsAuthenticationTicket (1, UserName, DateTime.Now, DateTime.Now.AddHours ( A),false, UserData); HttpCookie Cookies=NewHttpCookie (Formsauthentication.formscookiename, Formsauthentication.encrypt (Ticket));//Encrypt identity information, save to CookieRESPONSE.COOKIES.ADD (Cookie);

Now that the identity information is saved to the cookie, what if a scene needs to use the user ID or other information of the current user?
Then, we re-obtain the identity information in the cookie, then decrypt, and then deserialize the user entity is OK.

/// <summary> ///Get user login information/// </summary> /// <returns></returns>  PublicUsers GetUser () {if(HttpContext.Current.Request.IsAuthenticated)//Whether authentication is passed{HttpCookie Authcookie= Httpcontext.current.request.cookies[formsauthentication.formscookiename];//Get CookiesFormsAuthenticationTicket Ticket = Formsauthentication.decrypt (Authcookie.value);//decryptionreturnSerializehelper.instance.jsondeserialize<users> (Ticket.userdata);//deserialization} return NULL; } 

2. Permission Verification
The action Interceptor (overriding onactionexecuting) in MVC is used here to run the code in the interceptor before the action executes. It is also possible to verify that authentication is out of date.

/// <summary> ///Permission Validation/// </summary>  Public classAuthattribute:actionfilterattribute {/// <summary> ///Role Name/// </summary>  Public stringCode {Get;Set; } /// <summary> ///Verify permissions (this is done before action executes)/// </summary> /// <param name= "Filtercontext" ></param>  Public Override voidonactionexecuting (ActionExecutingContext filtercontext) {//If identity information existsif(!HttpContext.Current.User.Identity.IsAuthenticated) {Contentresult Content=NewContentresult (); Content.content=string. Format ("<script type= ' text/javascript ' >alert (' Please login first! '); window.location.href= ' {0} ';</script>", Formsauthentication.loginurl); Filtercontext.result=Content;} Else { string[] Role = CheckLogin.Instance.GetUser (). Roles.split (',');//Get all rolesif(! Role.contains (Code))//Verify Permissions{ //validation does not passContentresult Content =NewContentresult (); Content.content="<script type= ' text/javascript ' >alert (' permission validation does not pass! '); History.go ( -1);</script>"; Filtercontext.result=Content;} } } } 

So how do you call it in action? Here's a look at the code in HomeController.

 Public classHomecontroller:basecontroller {[Authattribute (Code="Admin")]//validation passed (This action allows admin to view only) PublicActionResult Index () {Users Modeluser=CheckLogin.Instance.GetUser ();returnView (modeluser);} [Authattribute (Code="User")]//validation does not pass PublicActionResult Index2 () {returnView ();} [Authattribute (Code="Admin")]//validation passed, exception occurred PublicActionResult Index3 () {returnView ();} } 

This allows you to control the permissions to the action.
3. Exception Handling
The above homecontroller is not to inherit controller, but to inherit our own definition of a basecontroller, then we look at Basecontroller write what?

 Public class //

Here Basecontroller only do one thing, is to add a errorattribute error interceptor, so long as the exception that occurs in the controller will be processed in Errorattribute, you can log to the database and other operations. So let's see how Errorattribute works.

/// <summary> ///error log (this is performed when controller exception occurs)/// </summary>  Public classErrorattribute:actionfilterattribute, Iexceptionfilter {/// <summary> ///Exception/// </summary> /// <param name= "Filtercontext" ></param>  Public voidonexception (Exceptioncontext filtercontext) {//Get exception information, save in storageException Error =filtercontext.exception;stringMessage = Error.message;//error MessagestringURL = HTTPCONTEXT.CURRENT.REQUEST.RAWURL;//Error occurred addressfiltercontext.exceptionhandled =true; Filtercontext.result=NewRedirectresult ("/error/show/");//jump to the error tip page} } 

Here you can catch the exception and jump to the friendly error prompt page. A few operations in MVC can be done in such a simple way that the code is available for download below the article.

Example download

ASP. NET MVC authentication, exception handling, permission validation (interceptor) Implementation code

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: info-contact@alibabacloud.com 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.