asp.net mvc5+ef6+easyui background Management system (-MVC) WEBAPI user authentication (2) __.net

Source: Internet
Author: User
Tags button type decrypt documentation ticket
Source: http://ymnets.cnblogs.com/
Series Catalog Preface:

Reviewing the previous section, we took advantage of the simple WEBAPI login and the same domain access and Cross-domain access to get token, you can jump to the previous section to download code to work together.

To continue the previous article, we will then demonstrate the use of the token to access the interface, manage the interface, and use the System Rights management interface to authorize each interface (Admin interface is a selective reading section, because you need to read the first Permission Management Section (section 18-27) to read this section) Development environment:

vs2015+ No database (analog data)

Sample code download access password 8CA3 Knowledge Points: WEBAPI permission validation applied to the actual to debug start: 1. Filter Verification

We also used the filter to verify the operation of the action permissions, the interface is no exception, in the action cut, each visit with token information, perhaps you can use the following in the HTTP request header to attach token

Add Filter Class: Supportfilter and Inherit authorizeattribute permission filter Onauthorization base class method

Using System.Linq;
Using System.Web;
Using System.Web.Http;

Using System.Web.Security; Namespace Apps.WebApi.Core {public class Supportfilter:authorizeattribute {//rewrite the validation method of the base class, join our custom ticket verification
            Certificate public override void Onauthorization (System.Web.Http.Controllers.HttpActionContext actioncontext) {
            URL gets token var content = actioncontext.request.properties["Ms_httpcontext"] as httpcontextbase; var token = content.
            request.querystring["Token"]; if (!string.
                IsNullOrEmpty (token)) {//Decrypt user ticket and verify user name password matches if (Validateticket (token)) {base.
                IsAuthorized (Actioncontext);
                else {handleunauthorizedrequest (actioncontext); }///If authentication information is not available and anonymous access is not allowed, return the unauthenticated 401 else {var attribute s = ActioncontExt. Actiondescriptor.getcustomattributes<allowanonymousattribute> ().
                Oftype<allowanonymousattribute> (); BOOL isanonymous = attributes.
                Any (a => a is allowanonymousattribute); if (isanonymous) base.
                Onauthorization (Actioncontext);
            else Handleunauthorizedrequest (Actioncontext);
            }///Verify username password (match session or database data) private bool Validateticket (string encrypttoken) { Decrypt ticket var strticket = Formsauthentication.decrypt (Encrypttoken).

            UserData;
            Get username and password from ticket var index = strticket.indexof ("&");
            String userName = strticket.substring (0, index);
            string password = strticket.substring (index + 1);
            Get session, not by stating that the user exits, or the session has expired var token = Httpcontext.current.session[username];
            if (token = = null) {return false; }//Contrast SessiThe token if (token) in on.
            ToString () = = Encrypttoken) {return true;

        return false; }
    }
}

Httpactioncontext is not able to get the parameters of the URL, you need to convert to HttpContextBase, this class I have a comment, it is easy to read.

1. From the URL to token, using the previous encryption method to uncover the token and draw the token in the user name

2. Get the token in session with user name

3.ValidateTicket validation to determine whether the token in the session is the same as the acquired. 2. Apply to the actual

At last, each action is annotated, and it is preferable to call the interface to determine whether the access

3. Run Debugging

Before debugging, we need to write point code to access

Modify Home Index Code

<script src= "~/scripts/jquery-1.10.2.min.js" ></script> <style>html,body{height:100%}.box{ Filter:progid:DXImageTransform.Microsoft.gradient (startcolorstr= ' #6699FF ', endcolorstr= ' #6699FF '); Background-image:linear-gradient (Bottom, #69F 0, #69F 100%); Background-image:-o-linear-gradient (bottom, #69F 0, #69F 100%); Background-image:-moz-linear-gradient (bottom, #69F 0, #69F 100%); Background-image:-webkit-linear-gradient ( Bottom, #69F 0, #69F 100%); Background-image:-ms-linear-gradient (bottom, #69F 0, #69F 100%); margin:0 auto;position: relative;width:100%;height:100%}.login-box{width:100%;max-width:500px;height:400px;position:absolute;top:50%; margin-top:-200px}@ @media screen and (min-width:500px) {. login-box{left:50%;margin-left:-250px}}.form{width:100%; max-width:500px;height:275px;margin:25px Auto 0 auto;padding-top:25px}.login-content{height:300px;width:100%; Max-width:500px;background-color:rgba (255,250,2550,.6); float:left}.input-group{margin:0 0 30px 0!important}.form-control,.input-group{height:40px}.form-group{margin-bottom:0!important}.login-title{padding:20px 10px;background-color:rgba (0,0,0, .6)}.login-title h1{margin-top:10px!important}.login-title small{color: #fff}.link p{line-height:20px;margin-top : 30px}.btn-sm{padding:8px 24px!important;font-size:16px!important} </style> <div class= "box" style= "margin" : 100px;height:400px;width:500px; " > <div class= "Login-box" > <div class= "login-title text-center" >  

Add a button and div to display the results:

We got the right data. If there is no token, our results will return a 401

You can download the code to set the breakpoint

You can debug the order of the program for token processing! Summary:

This section explains how to use token to access the interfaces that require authorization. Using the MVC filter, a priority is given to the permissions check when the action is invoked, thus completing the sample interface authorization for the user.

The above section is generally sufficient, if you (ˇˍˇ) want ~ Deeper and subtle granularity authorization, then to each interface for individual authorization

If you are interested, you can continue to read the following admin authorization for the API

--------------------------------------------------------------------------------------------------------an ugly split line----------- ------------------------------------------------------------------------------

Here's how to manage the interface, which requires that you have a 18-27-section permission to read the series. Because large departments take advantage of the previous management interface functions and code, is closely linked, but it does not matter, even if you do not study the previous series, you may also be able to obtain knowledge from this section. Knowledge Points:

1. Take the API interface from all class libraries

2. Management interface

3. Authorize the interface

4. In the filter Add permission to verify start:

Review our Module management:

Management is the action (opcode) in each controller

This is also true of our webapi, the opcode of each controller, which fills the data into the Sysmodule table and Sysmoduleoperation table in the WEBAPI runtime 1. Get all API interfaces in the class library

This really works and gets the interface that you can usually use to manage or automate the test interface

  The controller as a URL, the Aciton as an opcode inserted into the datasheet as permission settings, similar to the previous permission system
            //Get API Manager
            collection<apidescription> Apicoll = GlobalConfiguration.Configuration.Services.GetApiExplorer (). apidescriptions;
            Ilookup

The first foreach obtains the controller, and the second foreach obtains the action under the controller. You add this to the home index, and you can track the properties of the models in group and M, respectively.

Now you know how to add a watch.

            foreach (var group in apigroups) {string controllername = group.
                Key.controllername; ----------Insert Controller Rootmodel = M_BLL.
                GetByID (controllername);
                    if (Rootmodel = = null) {Sysmodulemodel model = new Sysmodulemodel () {Id = controllername, Name = Controllername, E Nglishname = "", ParentID = "Apiinterfaceauth", Url = "api/" + Controllerna Me, iconic = "Fa fa-television", Enable = True, Re
                        Mark = "API Interface Authorization", Sort = 1, Createperson = "Admin",
                    Createtime = DateTime.Now, Islast = true}; M_bll.
            Create (ref errors, model);    //-----------Insert action foreach (var m in group) {
                    string actionname = M.actiondescriptor.actionname;
                    Sysmoduleoperatemodel model = Operatebll.getbyid (m.actiondescriptor.actionname);
                        if (model = = NULL) {model = new Sysmoduleoperatemodel (); Model.
                        Id = Controllername + actionname; Model. Name = M.documentation = null?
                        Actionname:m.documentation; Model.
                        KeyCode = ActionName; Model.
                        ModuleID = Controllername; Model.
                        IsValid = true; Model.
                        Sort = 0;
                    Operatebll.create (ref errors, model); }

                }
            }

After running the database will be automatically added, a few data

2. Management interface

Table data and we are normal is no difference, in the interface to do a switch to do for the switch, I have a drop-down here to switch the type

Change the query condition when you switch the Drop-down

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.