In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces Web API how to achieve Basic basic authentication related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this Web API how to achieve Basic basic authentication article will have a harvest, let's take a look.
1. Why identity authentication is needed in WebApi
When we use WebApi, we all get data through URL. In other words, anyone who knows the URL address can access the background service interface at will, and can access or modify database data, which will lead to very serious consequences.
1. We do not add identity authentication, and anonymous users can access the API directly through url:
2. After the authentication is added, only the request with the ticket can access the corresponding interface.
Second, common authentication methods
The common authentication methods in WebApi are as follows:
FORM authentication
Integrated WINDOWS verification
Basic basic Certification
Digest Digest Certification
Third, Basic basic authentication Basic basic authentication principle
The basic principle of Basic authentication is to encrypt user information to generate Ticket, and every time the backend API interface is requested, the generated Ticket information is added to the header of the http request and passed to the backend for verification. The specific steps are as follows:
1. Verify the user name and password when logging in. If the verification is passed, the user name and password will be generated according to certain rules to generate the encrypted ticket information Ticket, and then the Ticket will be passed to the front end.
2. If the login is successful, the frontend defines a global variable to receive the Ticket information returned by the API API.
3. When the front-end interface initiates an ajax request for the back-end API interface, the Ticket information is added to the Head of the HTTP request, and the Ticket information is sent to the back-end API interface along with the http request.
4. Define a class in the backend WebApi service, which inherits from the AuthorizeAttribute class, and then revisit the OnAuthorization method in the parent class. In the OnAuthorization method, the Head of the http request is obtained through the actionContext parameter, and the Ticket information passed by the frontend can be obtained from the Head. Decrypt the Ticket to get the user name and password, and then verify that the user name and password are correct. If correct, the verification is passed. If incorrect, a 401 unauthorized error is returned.
4. Sample code for Basic basic authentication
Suppose we want to access the Get interface of the Users controller, and the interface method returns the List collection of type int.
1. Login API API using Newtonsoft.Json;using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Web.Http;using System.Web.Security;using WebApiBasicAuthorize.CustomerAttribute;using WebApiBasicAuthorize.Entity Namespace WebApiBasicAuthorize.Controllers {[BasicAuthorize] public class UsersController: ApiController {/ [AllowAnonymous] [HttpGet] public IHttpActionResult Login (string account,string password) {ReturnValueEntity entity = new ReturnValueEntity () / / to verify account and password if (account.ToUpper (). Trim (). Equals ("ADMIN") & & password.Trim (). Equals ("123456") {FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (0, account, DateTime.Now, DateTime.Now.AddHours (1), true, string.Format ("{0} & {1}", account) in a real production environment Password), FormsAuthentication.FormsCookiePath) Var result = new {Result = true, Ticket = FormsAuthentication.Encrypt (ticket)}; entity.Result = true; entity.Ticket = FormsAuthentication.Encrypt (ticket);} else {entity.Result = false; entity.Ticket = "";} return Json (entity) } [HttpGet] public IHttpActionResult Get () {List list = new List (); list.Add (1); list.Add (2); list.Add (3); list.Add (4); list.Add (5); return Json (list);}
Add the [AllowAnonymous] feature to the Login method to indicate that anonymous logins are allowed.
2. Basic authentication API using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Http;using System.Web.Http.Controllers;using System.Web.Security The namespace WebApiBasicAuthorize.CustomerAttribute {/ custom attribute is inherited from AuthorizeAttribute / public class BasicAuthorizeAttribute:AuthorizeAttribute {public override void OnAuthorization (HttpActionContext actionContext) {/ / get the Authorization attribute var authorization = actionContext.Request.Headers.Authorization from the header information of the current http request Request object / / determine whether the controller acquires the action method with AllowAnonymousAttribute feature, and if so, allow anonymous login to if (actionContext.ActionDescriptor.GetCustomAttributes (true). Count! = 0 | | actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes (true). Count! = 0) {base.OnAuthorization (actionContext) } else if (authorization! = null & & authorization.Parameter! = null) {/ / verify user logic if (ValidateTicket (authorization.Parameter)) {/ / verify that base.IsAuthorized (actionContext) } else {this.HandleUnauthorizedRequest (actionContext);}} else {/ / returns 401unauthorized status code this.HandleUnauthorizedRequest (actionContext) }} / verify Ticket information / private bool ValidateTicket (string encryptTicket) {/ / decrypt Ticket var strTicket = FormsAuthentication.Decrypt (encryptTicket) .UserData / / get user name and password from Ticket int index = strTicket.IndexOf ("&"); / / string strUser=strTicket string [] array = strTicket.Split ('&'); string strUser= array [0]; string strPwd = array [1] / / the decrypted user name and password should be used to verify the database in the real production environment. For demonstration convenience / / assume that the user name is Admin and the password is 123456 if (strUser.Equals ("Admin") & & strPwd.Equals ("123456")) {return true } else {return false;} 3. Frontend code permission authentication / / defines a global ticket variable, which is used to save the var ticket value of Ticket after a successful login. _ window.onload=function () {} Function Login () {$.ajax ({url: "http://localhost:20033/api/users?account="+$("#acc").val().trim()+"&password="+$("#pwd").val().trim(), type:" Get ", dataType:" json " "headers": {"Content-Type": "application/json", "cache-control": "no-cache"}, success:function (data) {if (result.Result) {ticket=data.Ticket } else {alert (failure);}}, error:function (data) {alert (data);}});}; function Test () {alert (ticket) $.ajax ({url:' http://localhost:20033/api/users', type: "Get", dataType: "json", beforeSend:function (XHR) {/ / add verification information XHR.setRequestHeader ('Authorization','BasicAuth' + ticket) to http's head before sending the XHR.setRequestHeader request }, success:function (data) {alert (data);}, error:function (data) {alert (data);}});} User name: password:
What needs to be explained here is that before sending the ajax request, we add Ticket information to the Head of the http request through XHR.setRequestHeader ('Authorization',' BasicAuth'+ Ticket);.
The effect of Basic authentication can be achieved through the above steps.
Note: the backend WebApi interface should be configured to allow cross-domain access.
4. Optimization
For each additional controller, you need to add a [BasicAuthorize] feature to the corresponding controller, and you can define a common controller parent class that inherits from ApiController, and then other controllers inherit the parent class.
This is the end of the article on "how Web API achieves Basic basic Certification". Thank you for reading! I believe that everyone has a certain understanding of "Web API how to achieve Basic basic certification" knowledge, if you want to learn more knowledge, welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.