In my hybrid development framework, integrated with WEBAPI access, this access not only enables easy data exchange, but also can be accessed on a variety of platforms, such as WinForm programs, Web sites, mobile apps and many other access methods, web The API is handled in a similar way to the interface processing rules provided, and it is also achieved by obtaining an access token (Accesstoken) to the server and then passing it to each Web API interface for data exchange processing. This essay focuses on the processing of WinForm Web API access in a hybrid framework.
1. Introduction of Web API access method
The hybrid development Framework mixes Web API interface access, WCF interface access, and direct access to the database in three ways to accommodate applications in a variety of scenarios, and is based on an interface of the façade layer for processing and encapsulation. is a very good elastic framework application, can be used for stand-alone software or LAN-based application software, but also for the application of distributed technology in the Internet environment, is a mature and stable, secure and efficient technical framework.
For a detailed introduction to this framework, you can look at my essay "Summary of features of the WinForm Hybrid development Framework" for a detailed understanding.
Here is the main focus on the Web API access, we know that if it is a generic interface, if published on the Internet, there will be a lot of access risk, so it is necessary to check the interface calls, ensure that the access token is valid, and the data changes, but also need to check the encrypted signature of the data, To ensure that our interfaces operate in a more secure environment.
The hybrid framework invokes the detailed process of the Web API interface, which can be applied through the Web API application architecture in the WinForm Hybrid Framework (3)--winfrom interface calls WEBAPI process decomposition, and WEB API application architecture in WinForm Hybrid Framework (1) "," Web API Interface Design Experience Summary "to understand.
2. Handling of interface access tokens for WEB APIs
Because we need to verify the identity of the interface access, it is generally required that our interfaces have a token parameter to identify the user identity, as shown below is the interface definition of the MVC controller for the Web API layer.
[HttpGet] public UserInfo getuserbyname (stringstring Token { // token Check, non-pass throws exception checkresult checkresult = Checktoken (token ); return Bllfactory<user>. Instance.getuserbyname (UserName); }
If we need to call this interface on the client, we need to pass in the token parameter, which means that the token token needs to be obtained before invoking any interface, so that we can prepare for the interface call behind us.
And this token generation is very important, need to be strictly issued, so you need to get the token of the method parameters for signature verification, such as the following code is the Webapi interface to generate token processing.
/// <summary> ///registering a user gets an access token interface/// </summary> /// <param name= "username" >User Login name</param> /// <param name= "password" >User Password</param> /// <param name= "signature" >Encrypt Signature String</param> /// <param name= "timestamp" >time Stamp</param> /// <param name= "nonce" >Random number</param> /// <param name= "AppID" >app Access ID</param>[HttpGet] PublicTokenresult Getaccesstoken (stringUsernamestringPasswordstringSignaturestringTimestampstringNoncestringAppID
That is, you need to pass in user name, password, encryption signature, timestamp, random number, application access ID and other information, so as to build an access token, through the user name, password, encryption signature verification, etc., can achieve the strict issuance of Access tokens (token) processing.
Before the client calls all the Web API interfaces, we need to get to the user's access token through the above Web API interface, for convenience, we can encapsulate a function in the client, through this function to obtain the corresponding access token, and then store it in the cache, Convenient interface access processing for each module.
/// <summary> ///helper classes for users to get tokens/// </summary> Public classAccesstokenhelper {Private Const stringAPPID ="APPID";//app ID, assigned by system administrator Private Const stringAppsecret ="Appsecret";//Application key, assigned by the system administrator Private Const stringDefault_api_url ="Http://localhost:9001/api/Auth/GetAccessToken";//default Debug Web API gets an authorized address /// <summary> ///set the signature parameters. ///because most of the interfaces of the Web API require authentication of the user's access token (Accesstoken), the user needs to use this step to obtain token information when logging in, and then continue with subsequent interface operations. ///the application ID, application key and other parameters used by the interface are distributed uniformly by the system administrator. /// </summary> Public Static BOOLGetaccesstoken (stringUsernamestringpassword) { BOOLresult =false; //configuration using the Web API mode, you need to build a login token to accessAppConfig config =NewAppConfig (); stringCallertype = config. Appconfigget ("Callertype"); stringApiurl = config. Appconfigget ("Authapiurl"); Apiurl=string. IsNullOrEmpty (Apiurl)?Default_api_url:apiurl; if(Callertype.equals ("API", StringComparison.OrdinalIgnoreCase)) { //using the API mode, you need to set special information in the cache varurl = apiurl +Signaturehelper.getsignatureurl (APPID, Appsecret); URL+=string. Format ("&username={0}&password={1}", username, password); Tokenresult Tokenresult= jsonhelper<tokenresult>. Convertjson (URL); Result= !string. IsNullOrEmpty (Tokenresult.access_token); if(Tokenresult = =NULL) { varMessage ="Error getting authorization information, please check the address is correct! "; Messagedxutil.showerror (message); } varSignatureInfo =NewSignatureInfo () {AppID=APPID, Appsecret=Appsecret, token= (Tokenresult! =NULL) ? Tokenresult.access_token:NULL }; CACHE.INSTANCE.ADD ("SignatureInfo", SignatureInfo); } returnresult; }
With this helper method, we can call this method to get the token when the user is logged in as soon as the program is started.
stringIP =Networkutil.getlocalip (); stringMACADDR =hardwareinfohelper.getmacaddress (); stringLoginName = This. TxtLoginName.Text.Trim (); stringPassword = This. txtPassword.Text; //If the access token cannot be obtained, the return BOOLHasgottoken =accesstokenhelper.getaccesstoken (loginName, password); if(!Hasgottoken) { return; }
Just now I mentioned the interface definition of the MVC controller of the Web API layer, which is usually followed by a token parameter, as shown in the following code
[HttpGet] public UserInfo getuserbyname (stringstring token) { // token Check, non-pass throws exception checkresult checkresult = Checktoken (token); return bllfactory<user>. Instance.getuserbyname (UserName); }
And in order to facilitate client invocation, it is generally simplified when the client invokes the Web API, taking away the token parameter, and extracting its value from the cache. The encapsulation code, such as the client invocation, is shown below.
public UserInfo getuserbyname (string
UserName) { var action = " getuserbyname " string URL = gettokenurl (action) + string . Format ( &username={0} " = Jsonhelper<userinfo>. Convertjson (URL); return result; }
One of the gettokenurl is that we build a connection string based on token and method name, and the function implementation is as follows.
/// <summary> ///get a connection that simply contains the token parameter/// </summary> /// <param name= "Action" >Controller Method Name</param> /// <returns></returns> protected stringGettokenurl (stringaction) { stringURL =""; if( This. SignatureInfo! =NULL) { varAppend =string. Format ("? Token={0}", Signatureinfo.token); stringBASEURL =Getbaseurl (); URL= Combindurl (BASEURL, action + append);//combination for full access address } Else { Throw NewArgumentNullException ("No SignatureInfo signature information is set inside the cache"); } returnURL; }
So eventually we can get a connection address similar to the following:
http://localhost:27206/api/account/getaccounttypelist?token= Eyj0exaioijkv1qilcjhbgcioijiuzi1nij9.eyjpc3mioiixiiwiawf0ijoxndyzntu3otazlcjqdgkioii3ogmyogrhnc01zjrjltqxyzitothknc1lymfk Ztm3yja4njuilcjuyw1lijoiywrtaw4ilcjjagfubmvsijoimcisinnoyxjlzgtlesi6ijeymzrhymnkin0.dysdbgx70xuixxbz3g3x3mkgh9zxl2zf9fzu8 fgvs0w
With this token-assembled URL, we can parse the JSON string of the access result and parse it into the corresponding data.
Of course, in the actual Web API development process, we can also use the Web API tools for interface debugging, as shown below.
The following 1-5 of the logo is to obtain token of the required signature data, of course, the connection also with a few account authentication required information, such as account password, the company and other information.
Of course we can also use the browser to test to get token information, but it is not so convenient.
WinForm Hybrid Development Framework access to Web API interface processing