Asp.net mvc permission filtering and single-point Logon (repeated logon prohibited), asp. netmvc

Source: Internet
Author: User

Asp.net mvc permission filtering and single-point Logon (repeated logon prohibited), asp. netmvc

1. Permission control is implemented using controller and action. There are many permission methods. Recently, the code for using control controller in development projects is as follows:

/// <Summary> /// user permission control /// </summary> public class UserAuthorize: authorizeAttribute {// <summary> // view displayed when authorization fails /// </summary> public string AuthorizationFailView {get; set ;} /// <summary> /// execute when requesting authorization /// </summary> /// <param name = "filterContext"> context </param> public override void OnAuthorization (AuthorizationContext filterContext) {// get the controller and action string controllerName = filt in the url request ErContext. routeData. values ["controller"]. toString (); string actionName = filterContext. routeData. values ["action"]. toString (); // obtain user information UserLoginBaseInfo _ userLoginInfo = filterContext. httpContext. session [Property. uerLoginSession] as UserLoginBaseInfo; // query which role operations can be performed based on the requested controller and action: This is the roleid of the query database. RoleWithControllerAction uses the 1, 2, 3, 4 format roleWithControllerAction = SampleData. roleWithControlle RAndAction. firstOrDefault (r => r. controllerName. toLower () = controllerName. toLower () & r. actionName. toLower () = actionName. toLower () & r. roleIds. contails ("3"); // if (roleWithControllerAction! = Null) {// role id of the current controller and Action that has the permission to operate this. roles = roleWithControllerAction. roleIds;} else {// The request failed to output an empty result filterContext. result = new EmptyResult (); // The prompt text HttpContext is displayed. current. response. write ("sorry, you do not have permission to operate! ");} Base. onAuthorization (filterContext);} // <summary> // custom authorization check (if False is returned, authorization fails) /// </summary> protected override bool AuthorizeCore (HttpContextBase httpContext) {// if (httpContext. user. identity. isAuthenticated) // {// string userName = httpContext. user. identity. name; // username of the current logon User // user User user = SampleData. users. find (u => u. userName = userName); // The current logon user object // if (user! = Null) // {// Role role = SampleData. roles. find (r => r. id = user. roleId); // The role of the currently logged on user // foreach (string roleid in Roles. split (',') // {// if (role. id. toString () = roleid) // return true; //} // return false; // else // return false; /// else // return false; // enter HandleUnauthorizedRequest return true ;} /// <summary> /// handle HTTP requests that failed authorization /// </summary> protected override void HandleUnauthorizedRequest (AuthorizationContext filterContext) {if (string. isNullOrWhiteSpace (AuthorizationFailView) AuthorizationFailView = "error"; filterContext. result = new ViewResult {ViewName = AuthorizationFailView };}}

 Ii. Single Sign-On is implemented using the application method

1. Record the current information after successful User Login

/// <Summary> /// restrict one user to log on only once. /// </summary> /// <returns> </returns> private void GetOnline () {string UserID = "1"; Hashtable SingleOnline = (Hashtable) System. web. httpContext. current. application [Property. online]; if (SingleOnline = null) SingleOnline = new Hashtable (); IDictionaryEnumerator idE = SingleOnline. getEnumerator (); string strKey = string. empty; while (idE. moveNext () {if (idE. value! = Null & idE. value. toString (). equals (UserID) {// already login strKey = idE. key. toString (); // The current user has been removed, SingleOnline. remove (strKey); System. web. httpContext. current. application. lock (); System. web. httpContext. current. application [Property. online] = SingleOnline; System. web. httpContext. current. application. unLock (); break; }}// SessionID if (! SingleOnline. containsKey (Session. sessionID) {SingleOnline [Session. sessionID] = UserID; System. web. httpContext. current. application. lock (); System. web. httpContext. current. application [Property. online] = SingleOnline; System. web. httpContext. current. application. unLock ();}}

 2. Use ActionFilter to implement Single-point logon. Each time you click the controller, the system queries and filters whether to log on elsewhere.

/// <Summary> /// user basic information filter /// </summary> public class LoginActionFilter: actionFilterAttribute {// <summary> // initialization address // </summary> public const string Url = "~ /Login/Index? Error = "; /// <summary> /// this method will be called before the action method is executed /// </summary> /// <param name = "filterContext"> context </param> public override void OnActionExecuting (ActionExecutingContext filterContext) {// obtain the url of the previous level // var url1 = filterContext. httpContext. request. urlReferrer; UserLoginBaseInfo _ userLogin = filterContext. httpContext. session [Property. uerLoginSession] as UserLoginBaseInfo; // whether the user logs in if (_ userLogin = nu Ll) {filterContext. Result = new RedirectResult (Url + "the logon time has expired. Please log on again! & Amp; url = "+ filterContext. httpContext. request. rawUrl);} else {filterContext. httpContext. session. timeout = 30;} // determine whether to log on to Hashtable singleOnline = (Hashtable) System elsewhere. web. httpContext. current. application [Property. online]; // determines whether the current SessionID exists if (singleOnline! = Null &&! SingleOnline. ContainsKey (HttpContext. Current. Session. SessionID) filterContext. Result = new RedirectResult (Url + "your account has been logged on elsewhere and you are forced to go offline! "); Base. onActionExecuting (filterContext );} /// <summary> /// after execution /// </summary> /// <param name = "filterContext"> </param> public override void OnResultExecuting (ResultExecutingContext filterContext Context) {// record the operation log and write it into the operation log var controllerName = filterContext. routeData. values ["controller"]; var actionName = filterContext. routeData. values ["action"]; base. onResultExecuting (filterContext );}

 3. the user Exits normally or abnormally exits. process the current user information and destroy the Session.

/// <Summary> /// Session destruction /// </summary> protected void Session_End () {Hashtable SingleOnline = (Hashtable) Application [Property. online]; if (SingleOnline! = Null & SingleOnline [Session. SessionID]! = Null) {SingleOnline. remove (Session. sessionID); Application. lock (); Application [Property. online] = SingleOnline; Application. unLock ();} Session. abandon ();}

The above section describes Asp.net mvc permission filtering and single sign-on (repeated logon prohibited). I hope this will help you. If you have any questions, please leave a message, the editor will reply to you in time!

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.