WEB API Application Architecture Overview analysis and Design Examples tutorial

Source: Internet
Author: User
Tags datetime sha1 sha1 encryption static class access database

1, the Web API core layer Design

In the current developed application scenario, we often need to access the WinForm client, app program, web program, and currently in the bustling micro-letter applications, such data should be provided by the same service, this is what we need to build the Web API platform, based on the above requirements, Many enterprises need to design the whole enterprise application system with the concept of Web API priority. As the core of the whole link, the Web API needs to take into account the aspects of uniformity, stability, and security in the whole core layer.


As we can see from the image above, the entire perimeter scenario is built around the Web API core layer, and if we put it in a different way, then the following design diagram shows us the application of micro-letters, app applications, Web applications, WinForm applications as Web API interface layer above an interface application layer to deal with, this is based on an API interface layer, access to multiple or multiple interface application layer, so as to build a rich enterprise data service applications.

Because the Web API layer acts as a common interface layer, we are very good at ensuring the data consistency of each interface application layer, if we consider the response-type integration processing, we can even put the micro-letter applications, app applications, Web applications to do a layer of web programs, even in order to take advantage of the specificity of their applications, These applications can also be done very similar, so that gives users a unified interface representation, greatly improve the user interface experience, users need almost no additional interface learning, you can be familiar with the entire application system modules use.


Under the entire WEBAPI can be consolidated through the business Logic layer data storage and external interface access to two parts of the work, that is, the data access layer, the external interface layer such a layered concept, if extended, we can also provide customers with some files, pictures, videos and other information of the file storage, Like the micro-letter multimedia API interface, so that the entire Web API interface layer for all access to the client to provide a rich data interface, so as to achieve a powerful and flexible access.

As mentioned above, if you consider the integrated processing of the response, we can even use micro-letter applications, app applications, Web applications to do a layer of web programs, in fact, the app layer can be divided into two types, one is the native app type, using native language such as Object C to develop iOS applications, Use Java to develop the native applications of Android; another is to encapsulate a portal's native frame + background response Web page, as shown in the following illustration.


Compared with the native application, using the Portal Frame + response page, the development efficiency is very fast, the upgrade maintenance cost can also be reduced a lot, compared to web development is always faster than using the original app development.

From the above architectural analysis, our web API as the core layer, we can develop a variety of enterprise business applications,


In the current more popular member management, customer management and other aspects, combined with the application of micro-letter catalysts, you can do more in line with the trend of movement, so as to achieve our "Internet +" application landing.

2. Application of Web API layer in WinForm hybrid framework

Similarly, in the WinForm interface, we can use the direct Access database, as well as access to distributed WCF services, can also enable it to access the Web API Data Services, so as to build a more adaptable, more powerful hybrid development framework model.

Security is convenient, direct access to the database, there is no public interface on the network, they are only in a stand-alone or LAN security environment, so just to ensure the security of the database can, generally through the encryption connection string way to achieve a certain limit can be.

The security of WCF services can be verified by X509 certificates, and can also be checked with custom user names, password authentication, and so on.

For the Web API, because it provides a stateless interface access, and often the Web API generally for a variety of client access needs, may need to publish on the public Web Access, so we need to pay more attention to the Web API interface Layer Security, which we detail later.

The new type of hybrid development framework, in addition to direct-attached database access traditional mode, WCF distributed access WCF Service access mode, but also access to API distributed access to the Web API interface model, their relationship constitutes a complete WinForm application system, as shown in the following figure.


The following diagram shows a module analysis diagram based on traditional Access database and distributed WCF Data Services, and around the core of the hybrid framework, we can build many loosely coupled modules to provide higher development efficiency for our WinForm application development integration.

The hybrid framework can be viewed as an advanced version of the WinForm framework, except that it is a complete business system, with all the supporting modules on the periphery (such as universal permissions, common dictionaries, general attachment management, General Manager ...). Have realized this kind of hybrid frame, so the use is very convenient, if the whole frame is simplified, it is in the original WinForm interface layer, use the interface to invoke the way, avoid and the business logic class of tight coupling relation. Because it is invoked through an interface, it can itself specify the implementation of the WCF by configuration, and therefore encompasses all the features of the WCF framework. After the Web API layer has been developed, the integration of the Web API layer is my next phase of work.


We further analyze the implementation details of the hybrid framework, the traditional WinForm Access database and WCF service access methods that were considered through a configuration module to determine whether to use direct access to the database or to access WCF services, both of which are unified onto a façade interface façade layer, If you take into account the Web API layer, a hybrid architecture, that is, the interface to add more than one Web API to the façade layer of the façade interface can be encapsulated. The architecture diagram for the entire framework is shown below.



Interface Access Classification for 3.WEB APIs

The Web API interface can be accessed in several categories:

1 One is the use of user tokens, 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 user information maintenance, password modification, or user contacts and other user identity-related data.

2 One is the use of security signatures for data submission. This way to submit the data, URL connection signature parameters are secured by a certain rule of encryption, the server received data after the same rules of security encryption, confirmed that the data has not been tampered with, and then data modification processing. Therefore, we can for different access methods, such as Web/app/winfrom and other access modes to specify different encryption keys, but the secret key is agreed between the two sides, not on the network connection transmission, the connection is generally the transmission of the AppID, The server uses this AppID to encrypt the signature parameters, this way, similar to the background of the micro-letter callback processing mechanism, they are through this process.

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

The following illustration shows the description and the approximate application scenario of these types of access methods.


4. The implementation of WEB API using secure signature

First of all, we register for users, we need to be recognized by the terminal launch, that is, they need to carry out security signatures, the background to confirm the validity of the signature, in order to achieve the normal user registration, or be forged data, the system loses its original meaning.


<summary>


Register User Information interface


</summary>


public interface Iuserapi


{


<summary>


Registered user processing, including user name, password, ID number, mobile phone and other information


</summary>


<param name= "JSON" > Registered user Information </param>


<param name= "signature" > Cryptographic signature String </param>


<param name= "timestamp" > Time stamp </param>


<param name= "nonce" > Random number </param>


<param name= "AppID" > Application access id</param>


<returns></returns>


Resultdata Add (Userjson json,


String signature, string timestamp, string nonce, string appid);


}

In fact, we get the user's token, but also the need for user security signature authentication, so that we effectively guarantee the user identity token access to legitimacy.


<summary>


System authentication and other basic interfaces


</summary>


public interface Iauthapi


{


<summary>


Register user get access token interface


</summary>


<param name= "username" > User login name </param>


<param name= "password" > user password </param>


<param name= "signature" > Cryptographic signature String </param>


<param name= "timestamp" > Time stamp </param>


<param name= "nonce" > Random number </param>


<param name= "AppID" > Application access id</param>


<returns></returns>


Tokenresult Getaccesstoken (string Username, string password,


String signature, string timestamp, string nonce, string appid);


}





The parameters described above, we mentioned a number of parameters, one is a cryptographic signature string, one is the timestamp, one is random number, one is the application of the Access ID, our general processing rules as shown below.

1 The Web API for a variety of applications access, such as app, Web, WinForm and other access-side allocation application AppID and communication key Appsecret, each side of each store.

2 The access side needs to carry the following parameters when requesting the Web API interface: Signature, timestamp, nonce, AppID, the signature is based on several parameters and encryption key generated.

3 when the Web API receives an interface call request, it must first check that the passed signature is legitimate, and then call the relevant interface after authentication.

The authentication process of the cryptographic signature on the server side (Web API side) refers to the handling of the interface of the micro-letter, and the processing logic is shown below.

1 Check whether the timestamp and system time difference in a reasonable time, such as 10 minutes.

2) Appsecret, timestamp, nonce three parameters are sorted in dictionary order

3 concatenation of three parameter strings into a string for SHA1 encryption

4 The encrypted string can be compared with signature, if the match is to identify the request originated from an application, the request is legal.

The C # side code checksum is shown below.

<summary>


Check the data integrity of the application access


</summary>


<param name= "signature" > Encrypted signature content </param>


<param name= "timestamp" > Time stamp </param>


<param name= "Nonce" > Random string </param>


<param name= "AppID" > Application access id</param>


<returns></returns>


Public Checkresult validatesignature (string signature, string timestamp, string nonce, String AppID)


{


Checkresult result = new Checkresult ();


result.errmsg = "Data integrity check does not pass";





Get access channel details based on AppID


AppInfo channelinfo = Bllfactory<app>. Instance.findbyappid (AppID);


if (channelinfo!= null)


{


#region Verify the source of signature parameters is correct


String[] Arrtmp = {Channelinfo.appsecret, timestamp, nonce};





Array.Sort (ARRTMP);


String tmpstr = String. Join ("", arrtmp);





Tmpstr = FormsAuthentication.HashPasswordForStoringInConfigFile (tmpstr, "SHA1");


Tmpstr = Tmpstr.tolower ();





if (tmpstr = = Signature && validateutil.isnumber (timestamp))


{


DateTime dttime = timestamp. ToInt32 (). Inttodatetime ();


Double minutes = DateTime.Now.Subtract (dttime). Totalminutes;


if (Minutes > Timspanexpiredminutes)


{


result.errmsg = "signature timestamp invalid";


}


Else


{


Result.errmsg = "";


Result.success = true;


Result.channel = Channelinfo.channel;


}


}


#endregion


}


return result;


}

Once we have completed a successful authentication of the security signature, that is, we have confirmed the source and integrity of the data submission, we can do more security-related operations, such as the operation to obtain the user's access token information as shown below.

The first step is to verify that the user's signature meets the requirements, match the requirements of the user information, and generate the user access token data JSON, returned to the caller.


5, the Web API use security token implementation

Through the above interface, we get the user access token, later and the user-related information call, we can pass through this token parameters can be passed, this token with some of the user's basic information, such as user ID, expiration time, etc., this token design ideas from the JSON Web Token (JWT) can refer to http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html, as well as GitHub project https:// GITHUB.COM/JWT-DOTNET/JWT.

Because the Web API call, is a stateless way of invocation, we pass token to convey our user information, so we only need to verify the token on it.

The JWT token generation logic is shown below


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

Check the code, is the token generated by the reverse process, get the appropriate information, and the token issued by the validity of the time to judge, generally can be agreed to a failure time, such as 1 days or 7 days, also do not have to set too short.


<summary>


Check the user's token validity


</summary>


<param name= "token" ></param>


<returns></returns>


Public Checkresult Validatetoken (string token)


{


The returned result object


Checkresult result = new Checkresult ();


result.errmsg = "Token check does not pass";





if (!string. IsNullOrEmpty (token))


{


Try


{


String DECODEDJWT = Jsonwebtoken.decode (token, sharedkey);


if (!string. IsNullOrEmpty (DECODEDJWT))


{


#region Check the contents of a token object


Dynamic root = Jobject.parse (DECODEDJWT);


string username = Root.name;


string UserID = Root.iss;


int jwtcreated = (int) Root.iat;





Validity of inspection token, valid for 7 days


TimeSpan t = (datetime.utcnow-new DateTime (1970, 1, 1));


int timestamp = (int) t.totaldays;


if (timestamp-jwtcreated > Expireddays)


{


throw new ArgumentException ("Invalid user token");


}





Successful checksum


Result.success = true;


Result.errmsg = "";


Result.userid = userid;


#endregion


}


}


catch (Exception ex)


{


Logtexthelper.error (ex);


}


}


return result;


}





In general, access token can not be permanently valid, for access to the issue of the renewal of the token, you may set a rule, only the latest token to use, and store it in the interface cache for comparison, the application system exit, the memory inside the token to remove it.

6, the development of ASP.net Web API

Above we define the General Web API interface, and implement the corresponding business implementation, if we need to create the Web API layer, we need to build a Web API project.


After you create the appropriate project, you can add a Web API base class for your project to facilitate the control of common interfaces.


Then we can create more application API controllers on the controller directory.


Finally, in order to unify all API interfaces is to return JSON way, we need to webapiconfig inside the code to set.

public static Class Webapiconfig


{


public static void Register (Httpconfiguration config)


{


Web API Configuration and services


Config. Setcorspolicyproviderfactory (New Corspolicyfactory ());


Config. Enablecors ();





Web API Routing


Config. Maphttpattributeroutes ();





Config. Routes.maphttproute (


Name: "Defaultapi",


Routetemplate: "Api/{controller}/{action}/{id}",


defaults:new {action = ' post ', id = routeparameter.optional}


);





Remove the JSON Formatter


Config. Formatters.remove (config. Formatters.jsonformatter);





Remove the XML Formatter


Config. Formatters.remove (config. Formatters.xmlformatter);


}


}


7, the Web API interface test

The next thing we need to do is add a business interface for specific testing, recommend using the WinForm project, do a test on each interface, or consider using a unit test as a way to look at a person's liking.

For example, if we want to test the user login interface, our test code is shown below.

<summary>


Generate Signature String


</summary>


<param name= "Appsecret" > Access secret key </param>


<param name= "timestamp" > Time stamp </param>


<param name= "nonce" > Random number </param>


private string Signaturestring (string Appsecret, string timestamp, string nonce)


{


String[] Arrtmp = {Appsecret, timestamp, nonce};





Array.Sort (ARRTMP);


String tmpstr = String. Join ("", arrtmp);





Tmpstr = FormsAuthentication.HashPasswordForStoringInConfigFile (tmpstr, "SHA1");


return Tmpstr.tolower ();


}





Private Tokenresult Gettokenresult ()


{


string timestamp = DateTime.Now.DateTimeToInt (). ToString ();


String nonce = new Random (). Nextdouble (). ToString ();


String signature = signaturestring (Appsecret, timestamp, nonce);





string appended = string. Format ("&signature={0}&timestamp={1}&nonce={2}&appid={3}", signature, timestamp, nonce, AppID);


String queryurl = URL + "auth/getaccesstoken?username=test&password=123456" + appended;





Httphelper helper = new Httphelper ();


String token = helper. Gethtml (Queryurl);


Console.WriteLine (token);


Tokenresult Tokenresult = jsonconvert.deserializeobject<tokenresult> (token);


return tokenresult;


}

If we have obtained the token, we pass parameters to the connection based on the token, and the test processing code for other data is shown below.

Getting access Tokens
Tokenresult Tokenresult = Gettokenresult ();

String queryurl = URL + "/contact/get?token=" + tokenresult.access_token;
Httphelper helper = new Httphelper ();
string result = Helper. Gethtml (Queryurl);
Console.WriteLine (result);


If you need post data, the calling code looks like this.

Use POST method


var data = new


{


Name = "John",


Certno = "123456789",


};


var postdata = data. Tojson ();





Queryurl = URL + "/contact/add?token=" + tokenresult.access_token;


Helper = new Httphelper ();


Helper. ContentType = "Application/json";


result = Helper. Gethtml (Queryurl, PostData, true);


Console.WriteLine (result);


The Web API background automatically converts the JSON data of the post to the corresponding object.

If it is a get way, we may be able to debug directly through the browser, if it is post way, we need to use some assistance tools, such as fiddler and other processing tools, but the best way is to get a test tool to facilitate testing.

Here's what I need to develop for my web API interface, a special debugging tool that automatically assembles related parameters, including using secure signature parameters, and storing all parameter data.



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.