Asp.net Mvc authentication, exception handling, permission Verification Code

Source: Internet
Author: User

For more information about Asp.net Mvc authentication, exception handling, and permission verification code, see.

This topic describes the authentication mechanism of asp.net and the application of asp.net MVC interceptor in the project. Now let's simulate a simple process: User Logon, permission verification, and exception handling.

1. User Logon
This document describes how to save the current user's logon information (session, cookie) after a user successfully logs on. This document describes identity authentication (in fact, it is based on cookies, next let's look at the code.

Introduce namespace

The Code is as follows: Copy code

Using System. Web. Security;
Users ModelUser = new Users () {ID = 10000, Name = UserName, UserName = UserName, PassWord = PassWord, Roles = "admin"}; // user entity
String UserData = SerializeHelper. Instance. JsonSerialize <Users> (ModelUser); // serialize user entities

// Save the identity information. For parameter description, see the prompt FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket (1, UserName, DateTime. Now, DateTime. Now. AddHours (12), false, UserData );
HttpCookie Cookie = new HttpCookie (FormsAuthentication. FormsCookieName, FormsAuthentication. Encrypt (Ticket); // Encrypt the identity information and save it to Cookie
Response. Cookies. Add (Cookie );

Now the identity information is saved to the cookie. What should I do if I need to use the user ID or other information of the current user?

Then, we get the identity information again in the cookie, decrypt it, And deserialize it into a user entity.

The Code is as follows: Copy code

/// <Summary>
/// Obtain user logon information
/// </Summary>
/// <Returns> </returns>
Public Users GetUser ()
{
If (HttpContext. Current. Request. IsAuthenticated) // whether the authentication is successful
{
HttpCookie authCookie = HttpContext. Current. Request. Cookies [FormsAuthentication. FormsCookieName]; // get cookie
FormsAuthenticationTicket Ticket = FormsAuthentication. Decrypt (authCookie. Value); // Decrypt
Return SerializeHelper. Instance. JsonDeserialize <Users> (Ticket. UserData); // deserialization
}
Return null;
}

2. Permission Verification
Here, the action interceptor in MVC (rewrite OnActionExecuting) is used. Before the action is executed, the code in the interceptor is run. Here, you can also verify whether the authentication has expired.

 

The Code is as follows: Copy code

/// <Summary>
/// Permission Verification
/// </Summary>
Public class AuthAttribute: ActionFilterAttribute
{
/// <Summary>
/// Role name
/// </Summary>
Public string Code {get; set ;}

/// <Summary>
/// Verify the permission (this will be executed before the action is executed)
/// </Summary>
/// <Param name = "filterContext"> </param>
Public override void OnActionExecuting (ActionExecutingContext filterContext)
{
// If identity information exists
If (! HttpContext. Current. User. Identity. IsAuthenticated)
{
ContentResult Content = new ContentResult ();
Content. Content = string. Format ("<script type = 'text/javascript '> alert ('Log On first! '); Window. location. href =' {0} '; </script> ", FormsAuthentication. LoginUrl );
FilterContext. Result = Content;
}
Else
{
String [] Role = CheckLogin. Instance. GetUser (). Roles. Split (','); // obtain all Roles
If (! Role. Contains (Code) // verify the permission
{
// Verification fails
ContentResult Content = new ContentResult ();
Content. Content = "<script type = 'text/javascript '> alert ('permission Verification Failed! '); History. go (-1); </script> ";
FilterContext. Result = Content;
}
}
}
}

So how to call it in action? Paste the code in HomeController here.

The Code is as follows: Copy code


Public class HomeController: BaseController
{
[AuthAttribute (Code = "admin")] // authentication passed (this action can only be viewed by the admin)
Public ActionResult Index ()
{
Users ModelUser = CheckLogin. Instance. GetUser ();
Return View (ModelUser );
}

[AuthAttribute (Code = "user")] // verification fails
Public ActionResult Index2 ()
{
Return View ();
}

[AuthAttribute (Code = "admin")] // verification passed, exception
Public ActionResult Index3 ()
{
Return View ();
}
}

In this way, you can control the permission to action.

3. Exception Handling
The above HomeController does not inherit the Controller, but a BaseController defined by ourselves. So let's take a look at what is written in BaseController?

The Code is as follows: Copy code
[ErrorAttribute]
Public class BaseController: Controller
{
// If all controllers inherit the BaseController, exception capture is performed.
}

Here, BaseController only does one thing, that is, it adds an ErrorAttribute error Interceptor. If exceptions occur in the Controller, they will be processed in ErrorAttribute, you can record operations to the database. Let's see how ErrorAttribute works.

 

The Code is as follows: Copy code

/// <Summary>
/// Error Log (this will be executed when the Controller encounters an exception)
/// </Summary>
Public class ErrorAttribute: ActionFilterAttribute, IExceptionFilter
{
/// <Summary>
/// Exception
/// </Summary>
/// <Param name = "filterContext"> </param>
Public void OnException (ExceptionContext filterContext)
{
// Obtain the exception information and store it in the database
Exception Error = filterContext. Exception;
String Message = Error. Message; // Error Message
String Url = HttpContext. Current. Request. RawUrl; // address where an error occurs

FilterContext. ExceptionHandled = true;
FilterContext. Result = new RedirectResult ("/Error/Show/"); // jump to the Error prompt page
}
}

Here you can capture exceptions and jump to the friendly error prompt page. Several operations in MVC can be simply done in this way, and the code will be downloaded below the article.

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: 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.