ASP (1)-MVC WEBAPI user authentication (Mvc5+ef6+easyui)

Source: Internet
Author: User
Tags httpcontext ticket

Series CatalogueObjective:

Webapi mainly Open data to the mobile phone app, other need to know the data system, or software applications, so the mobile end and the system's data source is often connected.

Web user authentication, and page Operation permission verification is the basic function of B/s system, a complex business application system, through role authorization to control user access

This article through Basic authentication MVC's controller base class and action authorization to implement the Web system login, MVC front-end permission check and WEBAPI server access check function, this article mainly as I forget to use, if can give people help, deeply honored, Welcome to discuss and correct, comb the verification process below

Development environment:

vs2015+ No database (analog data)

Knowledge Points:
    1. Webapi Simple to use
    2. User Check
    3. Same Domain access
    4. Cross-domain Access
Verification process:

1.WEBAPI server receives access request, need to do security authentication processing, verify the processing steps are as follows:

1) If it is a legitimate HTTP request, in the HTTP request header will have the user identity of the ticket information ( if the cross-domain can not add tickets in the request header ), the server will read the ticket information, and verify that the ticket information is complete and valid, if the verification requirements are met, the processing of business data, and returned to the requesting initiator;

2) If there is no ticket information, or the ticket information is not legal, return an "unauthorized access" exception message to the front end, which is handled by the front end.

2. Login and Authorization verification process

1) The user opens the browser, and enters the page request address in the Address field, submits;

2) The browser parses the HTTP request, sends it to the Web server, and the Web server verifies the user request, first of all to determine whether there is login ticket information;

3) The user does not have login ticket information, then jumps to the login page;

4) User input user name and password information;

5) The browser submits the login form data to the Web server;

6) The Web service needs to verify that the user name and password match, sending API requests to the API server;

7) API user account service according to the user name, read the user data stored in the database, determine whether the password matches;

7.1) If the user name and password do not match, then prompt password error and other information, and then the user re-fill the login information;

7.2) If the validation is passed, the user ticket information is saved;

8)

3. If the user has login ticket information, then jump to the user requested page;

9) To verify that the user is currently working on the page or page elements have permission to operate, first need to initiate the API service request, obtain the user's permission data;

). The API User Rights service locates the user's role information based on the user name and calculates a list of user permissions, encapsulated as JSON data and returned;

11). When the user has permission to manipulate the page or page element, jumps to the page and submits the Business data processing request to the API server by the page controller, and if the user does not have permission to access the page or page element, the "unauthorized access operation" is displayed and jumps to the system exception handling page.

). The API business service processes the business logic and returns the results as JSON data;

13). Returns the rendered page to the front of the browser and renders the business data to the page;

14). Users fill in business data, or find business data;

15). When the business data is completed or found, the user submits the form data;

16). Browser script submits get,post and other requests to the Web server, the Web server again resolves the request operation, repeating step 2 of the subsequent process;

17). When the API server verifies that the user is not a trusted user ticket, the system prompts for "unauthorized access operation" and jumps to the system exception handling page.

Start: 1. Add an empty Webapi, no authentication Webapi

2. New Account Controller AccountController
Using apps.common;using apps.webapi.models;using system;using system.collections.generic;using System.Linq;using System.net;using system.net.http;using system.web;using system.web.http;using system.web.security;namespace apps.webapi.controllers{public class Accountcontroller:apicontroller {[HttpGet] public Object Logi N (string userName, string password) {//The actual scene should be validated to the database if (userName! = "123" && PASSW            ord!= "123") {return Json (jsonhandler.createmessage (0, "Username or password error"));                            } FormsAuthenticationTicket token = new FormsAuthenticationTicket (0, UserName, DateTime.Now, DateTime.Now.AddHours (1), True, string.            Format ("{0}&{1}", UserName, password), formsauthentication.formscookiepath);            Returns login results, user information, user authentication ticket information var token = Formsauthentication.encrypt (token); Save the identity information in session to verify that the current request is a valid request for HTTPcontext.current.session[username] = Token;        Return Json (Jsonhandler.createmessage (1, Token)); }    }}

To verify the user name and password, there is no database demo, so the direct is to do a fixed match, account number 123, Password 123 (can refer to 19 user login, get the database check mode)

Logon failure: return error prompt

Login Successful: Return token and save token to Session

The visible code contains the operation of the session, but WEBAPI does not support session by default, so we need to add support for the session at global load, otherwise the run call will be directly abnormal

    protected void Application_postauthorizerequest ()    {        HttpContext.Current.SetSessionStateBehavior ( System.Web.SessionState.SessionStateBehavior.Required);    }
3. Running Webapi

Input Http://localhost:13743/help can see that our interface has been listed in Webapi Help and can look at the calling method (VS2012 may not be automatically generated WEBAPI and need to be obtained from the NuGet package)

4. Same domain invocation

Add a login code to the home index.cshtm

<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" > 

Running/home/index in the browser

Get token successfully

5. Cross-domain access

With domain name access, general system tasks This is safe and can be trusted, so do not need to do too much consideration, this is what we look at cross-domain scenarios

1. Easy to remember, set the port of the APPS.WEBAPI to a fixed 8866

2. Create a new WEB MVC normal no user authentication site Apps.web set port to 4455

Copy the 8866 Home/index login interface code to HOME/INDEX under 4455 and modify the access URL

URL: "Http://localhost:8866/api/Account/Login"

3. Set up the solution to start multiple projects and start 4455,8866

This is used to get 4455 to access the 6655 API, or absolute 404

The access succeeds, but there is no return value, jquery shows that jquery's JSONP format has callback returned

Set the AJAX datatype to JSONP

DataType: "Jsonp",

Run again, bring back the value normal

But the result does not pop up token and hints a JS error

It's twists to be here.

Because the value returned is: {"Id": "123"}

However JSONP needs you to return: jquery* ([{"Id": 123 "}])

4. Allow Webapi to support cross-domain return formats

Registering a global property

 using system.net.http;using system.text;using system.web;using system.web.http.filters;namespace apps.webapi.core{public class Jsoncallbackattribute:actionfilterattribute {Private Const string CALLBACKQ        Ueryparameter = "Callback"; public override void OnActionExecuted (Httpactionexecutedcontext context) {var callback = string.            Empty;                if (Isjsonp (out callback)) {var jsonbuilder = new StringBuilder (callback); Jsonbuilder.appendformat ("({0})", Context. Response.Content.ReadAsStringAsync ().                Result); Context.            Response.content = new Stringcontent (jsonbuilder.tostring ()); } base.        onactionexecuted (context); } private bool Isjsonp (out string callback) {callback = httpcontext.current.request.querystring[            Callbackqueryparameter]; Return!string.        IsNullOrEmpty (callback); }    }}
GLOBALCONFIGURATION.CONFIGURATION.FILTERS.ADD (New Jsoncallbackattribute ());

Run again:

The end of this section, the next section to learn how to use token for access to get permission

Resources:

Http://stackoverflow.com/questions/9594229/accessing-session-using-asp-net-web-api

Http://stackoverflow.com/questions/23698804/asp-net-mvc-with-forms-auth-and-webapi-with-basic-auth

Https://weblog.west-wind.com/posts/2013/apr/18/a-webapi-basic-authentication-authorization-filter

Http://stackoverflow.com/questions/17121964/asp-net-web-api-restful-web-service-basic-authentication

Http://www.cnblogs.com/Kummy/p/3767269.html

Instance code download access password 13DF

ASP (1)-MVC WEBAPI user authentication (Mvc5+ef6+easyui)

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.