Application of WEB API application architecture in WinForm Hybrid Framework (1)

Source: Internet
Author: User
Tags sha1 encryption

In the "Web API Application Architecture design Analysis (1)" and "Web API Application Architecture Design Analysis (2)" In the webapi of the structure of a certain analysis, in today's mobile-first slogan, the traditional platform has developed its own WEB API platform, convenient access to a variety of end systems, Many enterprise needs are based on the concept of Web API first to design the entire enterprise application system. As the core of the whole link, Web API needs to take into account the unity, stability, security and other factors throughout the core layer. This article focuses on the WEB API application architecture, the role in WinForm integration, and how to implement the integration case within the WinForm hybrid architecture.

1. Web API Introduction Review

The Web API is an application interface framework that can build HTTP services to support the framework of a wider range of clients (including mobile devices such as browsers, phones, and tablets), an ASP that is used to build RESTful applications on the. NET Framework The ideal platform for sequencing. In the present developed application scenario, we often need to access WinForm client, app, website program, and currently in a very enthusiastic application, such data should be provided by the same service, this is what we need to build the Web API platform. Because the Web API layer acts as a common interface layer, we guarantee the data consistency of each interface application layer.

From the above understanding, we can know that all external applications, in fact, can be based on an identical Web API core to carry out, as shown in.

In the current big platform, large application background, can be based on a whole platform to build a lot of application ecosystem, so you can use the Web API as the core layer, you can develop our various enterprise business applications.

2. Integration of WEB API in WinForm framework

In the WinForm interface, in addition to the direct access to the database, as well as access to distributed WCF services to access, but also to enable it to access the Web API Data Services, so as to build a more adaptable, more powerful hybrid development framework model; for web API, because it provides a stateless interface access, and often the Web API for a variety of client access needs, may need to publish on the public network for access, so we need to pay more attention to the security of the Web API interface layer.

In addition to the traditional mode of direct-attached database access, WCF distributed access to the WCF service access pattern can also access the API Distributed Access Web API interface pattern, their relationships constitute a complete WinForm application system, as shown in.

The implementation details of the hybrid framework are the use of a switch-mode-like configuration module to determine whether to direct access to the database, or how to access the WCF services, both of which are unified to a facade interface façade layer, if the Web API layer is considered, based on a hybrid architecture, That is, in this facade interface façade layer to add more than one Web API interface package into. The architecture diagram for the specific entire framework is shown below.

3. Security Considerations for WEB API Access

Because the Web API is Internet-based applications, so security is far more stringent than the local access to the database, based on common practice, the general use of a few thresholds to deal with these issues, one is based on the CA certificate of HTTPS data transmission, to prevent data eavesdropping, in particular, can refer to the Web API Application Support HTTPS experience summary, the second is to use the parameter encryption signature method to pass, the parameters passed, add an encryption signature, the server side to verify the signature content, to prevent tampering; third, to the general interface access, all need to use the user identity token for verification, Access to data is allowed only if the check is passed.

The way the Web API interfaces are accessed can be divided into several categories:

1) One is to use the user token, through the Web API interface for data access. This way, can effectively identify the user's identity, for the user interface to return user-related data, such as including user information maintenance, password modification, or user contacts and other user identity-related data.

2) One is to use a secure signature for data submission. The data submitted in this way, the URL connection signature parameters are secured by certain rules of encryption, the server received the data after the same rules of security encryption, verify that the data has not been tampered with, then the data modification processing. Therefore, we can specify different encryption keys for different access methods, such as Web/app/winfrom, but the secret key is agreed by both parties, and is not transmitted on the network connection, the connection transmission is generally the appid of this access, The server uses this AppID to perform cryptographic comparisons of signature parameters, which are similar to the callback processing mechanisms in the background, and they are handled in this way.

3) One way is to provide a public interface call, do not need to pass in the user token, or to encrypt the parameters of the signature, this interface is generally less, just provide some very regular data display.

Based on the above considerations, we generally need to design the interface of the Web API object, we need to consider the reasons for security, that is, we need to add some more field information.

If you can change these interfaces, in addition to incoming token information (identify specific users), also need to pass the signature information, as shown in the following interface.

        /// <summary>        ///inserts the specified object into the database/// </summary>        /// <param name= "info" >the specified object</param>        /// <returns>whether the operation was successful. </returns>         Public VirtualCommonresult Insert (T info,stringTokenstringSignaturestringTimestampstringNoncestringAppID

The above interface, in addition to the parameters created by the Info object for the object, several other parameters are added for security reasons.

In the interface, we need to verify the user's permissions and signature information, and then in the next step of data processing, if the checksum permissions and parameter integrity does not pass, it will be intercepted, do not perform the database processing.

            // If the user token check does not pass, the myapiexception exception is thrown.             // Check whether the user has permission or throw mydenyaccessexception exception            base. Checkauthorized (Authorizekey.insertkey, token, signature, timestamp, nonce, AppID);

In addition to these special interfaces to data modification, sometimes we also need to look for similar, not to change the interface of the data, only need to pass in the token, as shown in the following interface.

        /// <summary>        ///querying the database to see if an object with the specified ID exists/// </summary>        /// <param name= "id" >the ID value of the object</param>        /// <returns>The specified object is returned if it exists, otherwise null is returned</returns>[HttpGet] Public VirtualT FindByID (stringIdstringtoken) {            //If the user token check does not pass, the myapiexception exception is thrown. //Check whether the user has permission or throw mydenyaccessexception exception            Base.            Checkauthorized (Authorizekey.viewkey, token); T Info=Basebll.findbyid (ID); returninfo; }

We can see that token is still checked on the above, but there are many parameters such as date identification, random number, integrity check signature, application ID, etc. that are required for signing.

We will be based on the user token to resolve, if it is the normal token and can be resolved, then get the corresponding user's permission to determine whether the next process can be done.

If it goes through, then access the database and return the required data to the caller.

The above mentioned the user token, the user token is a similar real life pass, is through the user name, password and other information to obtain a security token, can be passed on multiple interfaces of the string, less password parameters of transmission, improve security.

This user token, generally generated by a separate interface, we generally put into the Authcontroller, the controller is responsible for user token-related processing calls.

        /// <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>        /// <returns></returns>Tokenresult Getaccesstoken (stringUsernamestringPassword,stringSignaturestringTimestampstringNoncestringAppID);

The code below is a specific business module, which shows how to get token tokens for manipulating various interfaces, and of course, in real-world situations, the HTTPS protocol is used to get the data, as shown in the demo code.

                stringAppID ="myapi_123456"; stringAppsecret ="Mysecret_2856fb9dbe31"; //using the API mode, you need to set special information in the cache                varURL ="Http://localhost:9001/api/Auth/GetAccessToken"+ Getsignatureurl (AppID, Appsecret) +"&username=admin&password="; Tokenresult result= jsonhelper<tokenresult>.                Convertjson (URL); if(Result = =NULL) {Messagedxutil.showerror ("Error getting authorization information, please check the address is correct! "); }

Because the invocation of the Web API is a stateless way of calling, we pass token to our user information, so we just need to verify token. The token generation logic for JWT is as follows

After the token is generated, we need to verify the token before the Web API call processing to ensure that the token is valid.

In addition to the rules of the token, there is a cryptographic signature processing, the cryptographic signature requires the client and server-side contract the same secret key, generally by the Web API is distributed uniformly, and then transferred, the client uses the application ID.

The processing logic for the cryptographic signature on the server side (Web API side) of the validation process reference interface is as follows.

1) Check whether the time difference between the timestamp and the system is within a reasonable time, such as 10 minutes.
2) dictionary ordering of three parameters of Appsecret, timestamp and nonce
3) concatenation of three parameter strings into a single string for SHA1 encryption
4) After the encrypted string can be compared with signature, if the match is identified that the request originated from an application, the request is legitimate.

4. Web API base class design analysis

The above describes some of the functions of the Web API controller, in general, we design a schema, we also need to consider the reuse of the base class objects, as far as possible to abstract the interface to the base class level, reduce the development of sub-class code, reduce maintenance costs.

Based on the above purpose, I refer to my web development framework for the MVC controller design Ideas

The Controller Design object inheritance relationship for the Web API is re-organized as follows:

Our key core is to design a good businesscontroller<b, t> This base class, which design a large number of common interfaces, including the normal additions and deletions, paging and other processing interfaces, then the subclass inherits to have these interfaces directly, How convenient AH.

5) Invocation of the Web API client (Hybrid WinForm Framework module)

The above describes the Web API server platform architecture design ideas, through the above integration, we have reduced the development of repetitive functions, such as the deletion and modification of the basic functions of the Controller code, these interfaces are abstracted into the interface can be achieved.

However, we should specifically how to follow the Uniform interface layer facade layer of the Convention, and then unified call WEBAPI layer interface, so that silently from the different data sources to obtain data, display in the client.

Above, we analyzed that the whole hybrid WinForm Framework module, the design aspects of the data to consider the aspects of access: including directly from the database, from the WCF service acquisition, as well as the Web API layer of data acquisition three parts of the content, Of course there are more data access modes (such as WebService, etc.), and the design effect is as follows.

All the data access, we in the facade layer are unified into the interface, the client's call also unified to callerfactory<t> this generic factory inside, we according to the configuration of different, from different modules loaded, so as to achieve the dynamic acquisition of different data sources.

The following logic is the load logic for the callerfactory<t> generic factory class, as follows:

In order to simplify the encapsulation of client calls, we generally also encapsulate the general general operation, as follows is the design of my original hybrid framework, the package is through the ***caller class to access data, these classes unified implementation of a certain relationship of integrated encapsulation.

In order to simplify the processing of the calling interface, the above relationship is simplified, and the processing of the calling wrapper class of the Web API is added, and the invocation side encapsulates the inheritance relationship in several access modes, as shown in the design diagram below.

At the bottom of the Dictdatacaller are the different access modes of the interface call wrapper class, for the Web API, its access code is as follows.

         Public Override BOOLDelete (stringkey) {            varAction ="Delete"; stringurl = Getposturlwithtoken (action) +string. Format ("&id={0}", key); Commonresult result= jsonhelper<commonresult>.            Convertjson (URL); returnresult.        Success; }                 PublicList<dictdatainfo> Findbytypeid (stringDicttypeid) {            varAction ="Findbytypeid"; stringurl = Gettokenurl (action) +string. Format ("&dicttypeid={0}", Dicttypeid); List<DictDataInfo> result = jsonhelper<list<dictdatainfo>>.            Convertjson (URL); returnresult; }

The first delete function is provided by the base class, which is overridden here, and generally does not need to be processed in a call to the underlying interface, such as adding or removing pages, to be packaged.

Since all implementation classes are implemented to inherit the interface of the unified facade layer, unified invocation is the natural thing. So in the WinForm interface, all calls are made using callerfactory<t> for unified processing, the different data access does not affect the interface processing, three ways of data calls, unity is the following code for processing.

dictdatainfo info = callerfactory<idictdataservice>. Instance.            FindByID (ID); if(Info! =NULL) {SetInfo (info); Try                {                    bool succeed = callerfactory<idictdataservice>. Instance. Update (info, info.id.                    ToString ()); returnsucceed; }                Catch(Exception ex) {logtexthelper.error (ex); Messagedxutil.showerror (ex.                Message); }            }

Application of WEB API application architecture in WinForm Hybrid Framework (1)

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.