. NET implements custom Contextuser identity and principal implement custom user information, permission validation. __.net

Source: Internet
Author: User
Tags httpcontext

. NET implements the identity and principal of custom Contextuser

In the traditional. NET, we can pass

        user.identity.name;//Get user name

        user.identity.isauthenticated;//judge whether the user has verified

        user.isinrole ("Admin"); To determine whether a user has a specified role


But such a mechanism, in the actual development, it is difficult to meet the development needs. It is difficult to meet the needs simply by User.Identity.Name, getting the username, and User.Identity.IsAuthenticated, and judging whether the user is validated. How to obtain more information about the user, or to make more detailed permission judgments.

We can implement it through custom identity and principal.

    <summary>///Customize the current user identity object///</summary> public class Myidentity:iidentity {

        #region User Properties (customizable for more information) private string _username;//user account private string _departmnet;//user's Department private string _phone;//user contact phone #endregion///<summary>///user account///</

        Summary> public string UserName {get {return _username;}

        ///<summary>///User Department///</summary> public string departmnet

        {get {return _departmnet;}

            ///<summary>///User phone///</summary> public string Phone {

        get {return _phone;} ///<summary>///Constructor, based on user name///</summary>///<param name= "UserName

    "></param> public myidentity (String UserName)    {///According to UserName query database for the following data This._username = "abc";

            this._departmnet = "Administrative Department";

        This._phone = "123456"; ///<summary>///Constructor, based on user ID///</summary>///<param name= "UserID" ></param> public myidentity (int UserID) {//To obtain the following data from the username query database thi

            S._username = "ABC";

            this._departmnet = "Administrative Department";

        This._phone = "123456"; #region Basic Properties///<summary>///return validation mode///</summary> Public str

        ing AuthenticationType {get {return "Form";}

        ///<summary>///Verify///</summary> public bool IsAuthenticated

        {get {true;}

      ///<summary>///return user///</summary> public string Name  {get {return _username;}

 } #endregion}


 

    <summary>///Current User security context information///</summary> public class Myprincipal:iprincipal { #region Property Private IIdentity _identity;//user identity private ArrayList _permissionlist;//permissions List #e Ndregion///<summary>///Returns a list of user rights///</summary> public ArrayList per

        Missionlist {get {return _permissionlist;}

        ///<summary>///get current User ID///</summary> public iidentity identity

        {get {return _identity;} ///<summary>///Whether the current user specifies a role (in the form of a permission value, returns false here)///</summary>///<p 

        Aram name= ' role ' ></param>///<returns></returns> public bool IsInRole (string role) {return false;//returns false}///<summary>///constructors, user name constructs/ </summary>///<param name= "UserName" ></param> public Myprincipal (string UserName) {

            _identity = new Myidentity (UserName);

            The following permissions are based on username to obtain the permission values that the database user has, this time omitting _permissionlist = new ArrayList ();

            _permissionlist.add (1);

            _permissionlist.add (2);

            _permissionlist.add (3);

            _permissionlist.add (4);

        _permissionlist.add (5); ///<summary>///Constructors, User ID constructs///</summary>///<param name= "UserID"

            ></param> public myprincipal (int UserID) {_identity = new myidentity (UserID);

            The following permissions are based on username to obtain the permission values that the database user has, this time omitting _permissionlist = new ArrayList ();

            _permissionlist.add (1);

            _permissionlist.add (2);

            _permissionlist.add (3);

            _permissionlist.add (4);

        _permissionlist.add (5);

   }     <summary>///Determines whether a user has a permission///</summary>///<param name= "PermissionID"

        ></param>///<returns></returns> public bool Ispermissionid (int PermissionID)

        {return _permissionlist.contains (PermissionID);

 }

    }


Well, above we have realized the custom, identity and principal.

We can use identity on the page like this.

The page outputs custom user information

<%= (user.identity as Contextuser.myidentity). Name%>//user account

<%= (user.identity as Contextuser.myidentity). Phone%>//subscriber

<%= (user.identity as Contextuser.myidentity). Departmnet%>//User Department


After customizing the display of user information, we then use principal for permission validation and control

In asp.net Web mode, use the following methods:

First, we'll do a privilege validation base class.

<summary>///Permission Validation base class///</summary> public class BasePaper:System.Web.UI.Page {public Basepaper () {////todo: Add constructor logic here//} protected override void O

    Ninit (EventArgs e) {basepage_load ();

        ///<summary>///Set permissions, the default value is 0///</summary> public virtual int PermissionID {

    get {return 0;}

    ///<summary>///Validation method///</summary>///<param name= "Sender" ></param>

        <param name= "E" ></param> private void Basepage_load () {//permission check #region permission check BOOL Permission = true;//Initial value is not authorized//This step is important to replace.

                NET's own user.

                Contextuser.myprincipal Myprincipal = new Contextuser.myprincipal (HttpContext.Current.User.Identity.Name);

        HttpContext.Current.User = Myprincipal; if (User as account. ContextUser.myprincipal). Permissionlist.contains (PermissionID)) {Permission = false;//authentication through} if (Permissio

            N)//permission validation does not pass {response.clear ();

            Response.Write ("<script language=\" javascript\ ">alert" ("Sorry, you do not have permission to enter \"); History.go ( -1);</script> ");

        Response.End ();

 } #endregion}}


OK, it's time to verify the page.

public partial class Ascx_add:basepage

{public

    override int PermissionID

    {get

        {return

            13;/ /Return to verify permission value

        }

    }

    protected void Page_Load (object sender, EventArgs e)

    {

        //

    }

}


In fact, in the ASP.net mvc pattern, permissions are easier to control, more refinement can be done, and each action is controlled.

In MVC mode:

First, implement a permission validation base class:

    <summary>///Permission Validation base class///2011.7.3///</summary> public class Basepage:authorize Attribute {///<summary>///permission value///</summary> private int _permiss

        Ionid = 0; <summary///Permission value///</summary> public int PermissionID {GE

            t {return _permissionid;}

        set {_permissionid = value;} 

        ///<summary>///is invoked when the procedure requests authorization. </summary>///<param name= "Filtercontext" > objects include the controller, HTTP context, request context, operation results, and routing data. </param> public override void Onauthorization (AuthorizationContext filtercontext) {i F (HttpContext.Current.User.Identity.IsAuthenticated) {//This step is important to replace.

                NET's own user.

       Contextuser.myprincipal Myprincipal = new Contextuser.myprincipal (HttpContext.Current.User.Identity.Name);         HttpContext.Current.User = Myprincipal; if (! Myprincipal.ispermissionid (_permissionid)) && (_permissionid!= 0)) {Httpco ntext.

                    Current.Response.Clear (); HttpContext.Current.Response.Write ("<script Defer>window.alert" is not authorized to operate.

                    '); History.back ();</script> ");

                    HttpContext.Current.Response.End ();

                Filtercontext.result = new Emptyresult ();

                } else {formsauthentication.signout ();

                HttpContext.Current.Response.Clear (); HttpContext.Current.Response.Write ("<script Defer>window.alert" is not authorized to operate. or the current logged-on user has expired. \\n Please log in again or contact the administrator.

                ');</script> ");

                HttpContext.Current.Response.End ();

            Filtercontext.result = new Emptyresult ();

 }

        }

 

    }


Back to the controller for permission validation

        [BasePage (PermissionID = 13)]//Return to verify permission value public

        actionresult Index ()

        {

           //

        }


Regardless of the ASP.net form or aap.net MVC, there is a button-level permission control,

That's how the button-level permissions are controlled.

Look at the code below.

    Controls the display of the delete

    <% if (User as account. Contextuser.myprincipal). Permissionlist.contains ({%>

    <input type= "Submit" name= "button" id= "button" value= "delete"/>

    <%} %>


At this point, how to implement custom identity and principal, to consolidate more user information, and permissions validation. I have already introduced the finished article.

More questions, please join us. NET Technology Group. Group number is: 160046333, welcome to join.

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.