Basic permissions validation for ASP. NET MVC View and Web API

Source: Internet
Author: User
Tags ticket

ASP. NET MVC 5.0 has been released for some time, adapted for some time, ready to refactor the original MVC project, the basic permissions to verify this piece of the record.

Environment: Windows 7 Professional SP1 + Microsoft Visual Studio (MVC 5 + Web API 2)

Modify the Web. config, add the forms validation mode, and add the following configuration to the system.web node:

 <authentication mode= "Forms" > Span style= "color: #0000ff;" ><forms loginurl= " ~/login " Defaulturl=" ~/"  Protection=" All " Timeout= " Name=" __ Auth "/></ Authentication>         

"MVC View Controller Chapter"

Create a new Pageauth, inherited from Authorizeattribute:

Using System;  Using system.net;  Using system.web;  Using SYSTEM.WEB.MVC;  Using System.Web.Security;       
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, inherited =True, AllowMultiple =True)]PublicClasspageauth:authorizeattribute{ProtectedOverrideboolAuthorizecore (HttpContextBase HttpContext) {if (HttpContext = =Null) {ReturnFalse; }if (httpContext.User.Identity.IsAuthenticated &&Base. Authorizecore (HttpContext)) {ReturnValidateUser (); } HttpContext.Response.StatusCode = (Int) Httpstatuscode.forbidden;ReturnFalse; }PublicOverridevoidOnauthorization (AuthorizationContext filtercontext) {Base. Onauthorization (Filtercontext);if (FilterContext.HttpContext.Response.StatusCode = = (Int) {Filtercontext.result = Httpstatuscode.forbidden)New Redirecttorouteresult ("accesserrorpage", null);}} protected override void handleunauthorizedrequest (AuthorizationContext filtercontext) { FilterContext.HttpContext.Response.Redirect (Formsauthentication.loginurl); } Private bool ValidateUser () { //TODO: Permission validation return true;}}   

Build a controller's base class Pagebase, inherited from controller:

Using SYSTEM.WEB.MVC;
[Pageauth]  class pagebase:controller{} 

All view controllers inherit from Pagebase and no longer inherit from the controller.

After inheriting the pagebase, all controllers are required to log in and add allowanonymous (for example, AccountController) to the controller (or action) that allows anonymous access:

Using SYSTEM.WEB.MVC;
PublicClassaccountcontroller:pagebase{[allowanonymous]Public ActionResult Login () // can be accessed anonymously {viewbag.title = " User login "; return View ();} Public ActionResult Detail (int id) // Required login access {viewbag.title = " User details "; return View ();}}                

Page controller development, the basic end of the next is the login page (~/login) using JS to submit login information, post.

After submission, the interface for the Web API needs to be developed.

"MVC Web API Controller Chapter"

Similarly, create a new Apiauth that inherits from ActionFilterAttribute:

Using System;  Using system.net;  Using System.Net.Http;  Using System.Web.Http;  Using System.Web.Http.Controllers;  Using System.Web.Http.Filters;  Using System.Web.Security;           
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, inherited =True, AllowMultiple =True)]PublicClassapiauth:actionfilterattribute{PublicOverridevoidOnActionExecuting (Httpactioncontext actioncontext) {Try{if (actioncontext.actiondescriptor.getcustomattributes<allowanonymousattribute> (). Count >0)//Allow Anonymous access{Base. OnActionExecuting (Actioncontext);Return; }var cookie =ActionContext.Request.Headers.GetCookies ();if (cookie = =null | | Cookies. Count <1) {Actioncontext.response =NewHttpresponsemessage (Httpstatuscode.forbidden);Return; } FormsAuthenticationTicket ticket =Null;foreach (var PercookieIn cookie[0]. Cookies) {if (Percookie.name = =Formsauthentication.formscookiename) {ticket = Formsauthentication.decrypt (Percookie.value); breakif (Ticket = = nullnew Httpresponsemessage ( Httpstatuscode.forbidden); return// TODO: Add additional validation methods base< Span style= "color: #000000;" >. OnActionExecuting (Actioncontext); } catch {Actioncontext.response = new Httpresponsemessage (Httpstatuscode.forbidden);}}      

Create a new Apicontroller base class Apibase, inherited from Apicontroller:

Using System.Web.Http;
[Apiauth]  class apibase:apicontroller{} 

Controllers from all APIs inherit from Apibase and no longer inherit from Apicontroller.

After inheriting apibase, add allowanonymous (for example, Logincontroller) to the controller (or action) that allows anonymous access:

Using System.Web.Http;  Using System.Web.Security; 
PublicClasslogincontroller:apibase{[HttpPost] [allowanonymous]PublicboolLogin ([Frombody]logininfo logininfo) {Try{var cookie = Formsauthentication.getauthcookie ("Username",False); var ticket = Formsauthentication.decrypt (cookie. Value); var newticket = new FormsAuthenticationTicket (ticket. Version, ticket. Name, ticket. IssueDate, ticket. expiration, ticket. Ispersistent,  "" ); Cookies. Value = Formsauthentication.encrypt (Newticket); DEYICONTEXT.RESPONSE.COOKIES.ADD (cookie); return truecatch {return false< Span style= "color: #000000;" >; } }} 

"Write at the end"

There are many methods on the Internet, and it takes time to verify the rationality of each method.

Regarding the security of the Web API, personally, it is more secure to use SSL.

In addition, a lot of writing online in the Web API permissions to judge, using the actionContext.Request.Headers.Authorization to judge, as follows:

Null) {    //To determine if anonymous access is allowed }elsevar ticket =// Subsequent other validation actions}    

Have not finished testing the method, take it easy ~ ~ ~

Basic permissions validation for ASP. NET MVC View and Web API

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.