ASP login and User role verification

Source: Internet
Author: User
Tags decrypt

Use ASP. NET MVC for login and role verification.

I am the most in want to achieve the site of the user Rights management issues, different roles of users access to the page to receive permissions restrictions. However, because of the empty project, it is only possible to manually implement the functions of role management.

The basic idea is to overload the Authorizeattribute attribute tag, allowing the overloaded class to inherit the Actiofilterattribute class to implement the character validation tag.

The login controller is written mainly to identify the user information from the database and the login information with ticket encryption stored in the cookie.

The following code is the login controller code

namespaceaccesscontrolsystem.controllers{ Public classAccesscontroller:controller {PrivateAccessControlContext db =NewAccessControlContext (); [HttpGet] PublicActionResult Login () {returnView (); } [HttpPost] [Validateantiforgerytoken] Publicactionresult Login (Login login) {varUsers = db. Users.where (A = A.name = =Login.            UserName); if(!users. Any ())returnView (); User User=users.            First (); varCards = db. Cards.where (A = a.user_id = =user.            ID); Card Card=cards.            First (); if(Login. password=="123"&&card. privilege==2) {FormsAuthenticationTicket Ticket=NewFormsAuthenticationTicket (1, Login. UserName, DateTime.Now, DateTime.Now.AddMinutes ( -),                    false,                    "Admin"                   ); varCookie =NewHttpCookie (Formsauthentication.formscookiename, Formsauthentication.encrypt (Ticket)); Cookies. HttpOnly=true;                HTTPCONTEXT.RESPONSE.COOKIES.ADD (cookie); returnRedirecttoaction (".. /database/selectuser"); }            returnRedirecttoaction ("Login"); }    }}

Using [HttpPost] to submit the form, where login uses only one variable, you can also add a string ReturnUrl variable to redirect to a page that previously did not have permission by using the redirect () method.

The core part of the code above is the if code, Formsauthenticationticket.ticket is the ticket we want to encrypt, the more important is login.username, and "admin" is stored in ticket name, The UserData.

Then Encrypt (Formsauthentication.encrypt (Ticket)) after the ticket exists in the value of the cookie.

The following code is an overload of the Authorizeattribute

namespaceaccesscontrolsystem.controllers{ Public classAuthenticationattribute:actionfilterattribute { Public Override voidonactionexecuting (ActionExecutingContext filtercontext) {stringRole =""; varCookie =Filtercontext.httpcontext.request.cookies[formsauthentication.formscookiename]; if(Cookie! =NULL)            {                varTicket =Formsauthentication.decrypt (cookies.                Value); Role=ticket.            UserData; }            if(role. length==0|| role!="Admin") {Filtercontext.result=NewRedirecttorouteresult (NewRouteValueDictionary (New{Controller ="Access", action ="Login" })); }            Base.        OnActionExecuting (Filtercontext); }    }}

In this code we read the value of the cookie from Filtercontext and let it pass through Formsauthentication.decrypt (cookie. Value) Decrypts the ticket information, and the UserData in the ticket stores the permissions of our users.

After defining this class, we can add [authentication] attribute tags before other methods to filter the user's permissions, in this instance only the user with "admin" can access, of course I do not use [Authentication (role= "admin") ] Method of

Since I haven't studied how to inherit roleprovider or how to implement the IPrincipal interface, I'm not using role I should update the implementation of both methods later.

Here is my definition of the login interface

@model accesscontrolsystem.models.login@{viewbag.title = "View";}<H2>Login</H2>@using (Html.BeginForm ()) {@Html. AntiForgeryToken (); @Html. ValidationSummary (True, "", new {@class = "Text-danger"})<fieldsetclass= "Form-horizontal">        <Divclass= "Form-group">@Html. Labelfor (Model=>model. username,htmlattributes:new {@class = "Control-label col-md-2"})<Divclass= "Col-md-10">@Html. Editorfor (Model=>model. username,new {htmlattributes=new {@class = "Form-control"}}) @Html. Validationmessagefor (Model=>model. UserName, "", new {@class = "Text-danger"})</Div>        </Div>        <Divclass= "Form-group">@Html. Labelfor (Model=>model. Password, htmlattributes:new {@class = "Control-label col-md-2"})<Divclass= "Col-md-10">@Html. Editorfor (Model=>model. password,new {htmlattributes=new {@class = "Form-control"}}) @Html. Validationmessagefor (Model=>model. UserName, "", new {@class = "Text-danger"})</Div>        </Div>        <Divclass= "Form-group">            <Divclass= "Col-md-offset-2 col-md-10">                <inputtype= "Submit"value= "Submit"class= "Btn Btn-default" />            </Div>        </Div>    </fieldset>}

Because it's just contacting ASP. What's wrong with that?

ASP login and User role verification

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.