Reprint Address: http://www.cnblogs.com/codeon/p/6123863.html
The previous article talked about the design of interface security, if you do not see the previous blog, it is recommended to see this after reading.
Through the discussion of the park friends, as well as I check some of the information, and then to the interface security to do a relatively perfect summary, committed to everyone to write a demo, released today.
For security is also relative, let me follow the security level analysis
1. Fully-Open Interface
There is no such interface, anyone can call, anyone can access, not limited by the time space, as long as the internet can be connected to the call, there is no security to say.
To tell you the truth, such interface we are in contact every day, you check the courier, you check the weather forecast, you check the plane, train frequency, and so on, these are public interfaces.
I call this the bare-Ben era. The code is as follows:
/// <summary> ///interface Open to the outside/// </summary> /// <returns></returns>[HttpGet] [Route ("nosecure")] PublicHttpresponsemessage Nosecure (intAge ) { varresult =Newresultmodel<Object>() {ReturnCode=0, Message=string. Empty, Result=string. Empty}; varDataresult = Stulist. Where (T = = T.age = =Age ). ToList (); Result. Result=Dataresult; returngethttpresponsemessage (Result); }
2. Interface parameter encryption (basic encryption)
You write an interface, you just want a specific caller to use, you call these people to a small room, and announce to them that I have an interface here is only intended for you, I give each of you a key, you use this key can be held.
This key is the parameter encryption rule I mentioned above, which can be called with this rule.
There is a security problem ah, if one of the members who accidentally lost the key or stolen, the master key can also come off the interface? And he can copy a lot of keys to the shady people.
The equivalent of someone to get your request link, if the business does not judge the link uniqueness (in fact, the business logic usually does not record each request encryption signature, so do not make a unique judgment), will be repeated calls, there is a certain security loopholes, how to break? Look at the code of this scene first, and then continue looking down!
/// <summary> ///Interface Encryption/// </summary> /// <returns></returns>[HttpGet] [Route ("securebysign")] PublicHttpresponsemessage securebysign ([Fromuri]intAgeLong_timestamp,stringAppKey,string_sign) { varresult =Newresultmodel<Object>() {ReturnCode=0, Message=string. Empty, Result=string. Empty}; #regionVerifying that the signature is legitimatevarparam =Newsorteddictionary<string,string> (Newasciicomparer ()); Param. ADD (" Age", age. ToString ()); Param. ADD ("AppKey", AppKey); Param. ADD ("_timestamp", _timestamp. ToString ()); stringCurrentsign =signhelper.getsign (param, AppKey); if(_sign! =currentsign) {result. ReturnCode= -2; Result. Message="The signature is illegal ."; returngethttpresponsemessage (Result); } #endregion varDataresult = Stulist. Where (T = = T.age = =Age ). ToList (); Result. Result=Dataresult; returngethttpresponsemessage (Result); }
3. Interface parameter encryption + interface timeliness verification (generally this level has been very safe)
In the last step, you find that someone who has a shady person calls your interface, you're upset, then call the person who really needs to call the interface and tell them to change their keys every day. As usual, there are individual partners of the key was small sneak away, the thief painstakingly, after several days of casing observation, prepared in a month of black and high night hands. Take out the key, and you can not open your sacred door for a long while, because thieves do not know that you are changing the new keys every day.
The thief disobeyed, after a period of time pondering, the thief found you change the key law. Once you get the key, don't think about it, do it on the same day, because he knows the key in his hand will expire the next day after you change the key.
As a result, the thief wished. How did it break? Look at the code of this scene first, and then continue looking down!
/// <summary> ///interface Encryption and judging validity based on time stamp/// </summary> /// <returns></returns>[HttpGet] [Route ("securebysign/expired")] PublicHttpresponsemessage securebysign_expired ([Fromuri]intAgeLong_timestamp,stringAppKey,string_sign) { varresult =Newresultmodel<Object>() {ReturnCode=0, Message=string. Empty, Result=string. Empty}; #regionDetermine if the request is out of date---assume that the expiration time is 20 secondsDateTime RequestTime=getdatetimebyticks (_timestamp); if(Requesttime.addseconds ( -) <datetime.now) {result. ReturnCode= -1; Result. Message="interface Expires"; returngethttpresponsemessage (Result); } #endregion #regionVerifying that the signature is legitimatevarparam =Newsorteddictionary<string,string> (Newasciicomparer ()); Param. ADD (" Age", age. ToString ()); Param. ADD ("AppKey", AppKey); Param. ADD ("_timestamp", _timestamp. ToString ()); stringCurrentsign =signhelper.getsign (param, AppKey); if(_sign! =currentsign) {result. ReturnCode= -2; Result. Message="The signature is illegal ."; returngethttpresponsemessage (Result); } #endregion varDataresult = Stulist. Where (T = = T.age = =Age ). ToList (); Result. Result=Dataresult; returngethttpresponsemessage (Result); }
4. Interface parameter encryption + timeliness verification + private key (to achieve this level of security impregnable)
Following the previous step, you find that however persuasive outsmart still has a theft thing happening. What do we do? You are going to lose the whole, give everyone a key to the foundation, and then send a signal to everyone, even if the key was stolen by thieves, thieves do not have the password, but can not be. Even if the thief really wish, so it is easy to locate the secret code leaks, to find the root cause of the problem, only need to give the current person to replace the key on the line, do not have to make a fuss.
But this is not foolproof, because the key and password after all, it is possible to get caught by thieves. The code is as follows:
/// <summary> ///interface encryption and validation based on timestamp and with private key check/// </summary> /// <returns></returns>[HttpGet] [Route ("Securebysign/expired/keysecret")] PublicHttpresponsemessage Securebysign_expired_keysecret ([Fromuri]intAgeLong_timestamp,stringAppKey,string_sign) { //Key Collection, here's a random two test data//if the caller is more, need to audit authorization, according to certain rules to generate key to store the data in the database, if the function expands, can be different for the caller to do different function rights Management//when the interface is invoked dynamically from the library, each caller with his key on the call, the caller generally put their own key in the site configurationdictionary<string,string> keysecretdic =Newdictionary<string,string>(); Keysecretdic.add ("Key_zhangsan","d9u7yy5d7ff2748aed89e90hj88881e6");//Zhang San's key,Keysecretdic.add ("Key_lisi","i9o6zz3d7ff2748aed89e90zb7732m9");//John Doe's key varresult =Newresultmodel<Object>() {ReturnCode=0, Message=string. Empty, Result=string. Empty}; #regionDetermine if the request is out of date---assume that the expiration time is 20 secondsDateTime RequestTime=getdatetimebyticks (_timestamp); if(Requesttime.addseconds ( -) <datetime.now) {result. ReturnCode= -1; Result. Message="interface Expires"; returngethttpresponsemessage (Result); } #endregion #regionGet the key value based on AppkeystringSecret = Keysecretdic.where (T = = T.key = =AppKey). FirstOrDefault (). Value; #endregion #regionVerifying that the signature is legitimatevarparam =Newsorteddictionary<string,string> (Newasciicomparer ()); Param. ADD (" Age", age. ToString ()); Param. ADD ("AppKey", AppKey); Param. ADD ("Appsecret", secret);//Add the secret to encryptparam. ADD ("_timestamp", _timestamp. ToString ()); stringCurrentsign =signhelper.getsign (param, AppKey); if(_sign! =currentsign) {result. ReturnCode= -2; Result. Message="The signature is illegal ."; returngethttpresponsemessage (Result); } #endregion varDataresult = Stulist. Where (T = = T.age = =Age ). ToList (); Result. Result=Dataresult; returngethttpresponsemessage (Result); }
5. Interface parameter encryption + timeliness verification + private key +https (I call this level the Admiralty Hood, the world's safest is this)
Following the previous step, we have changed the transmission mechanism to HTTPS, the thief completely confused forced. So what's the problem, https? You can set up a local environment, reference this article: http://www.cnblogs.com/naniannayue/archive/2012/11/19/2776948.html
Another: The interface of this article is written in MVC Webapi, completely based on the restful standard. If you are not particularly aware of this, you can refer to this article: http://www.cnblogs.com/landeanfen/p/5501490.html
Full demo Download
Note: The demo cannot be run directly, you need to configure two Web projects to IIS, the API represents the interface provider, his primary domain needs to be configured into business Webconfig, and in the browser address bar request each calling interface method in business to implement the interface call.
1, if you want to verify the parameter error, you need to make a breakpoint in the request interface to remove the interface URL, tamper with the URL parameters, and then impersonate the request in the browser
2, if you want to verify the interface timeout, you need to make a breakpoint in the request interface to take out the interface URL, and then wait for the timeout period, and then impersonate the request in the browser
3, if you want to verify the private key error, you need to make a breakpoint at the request interface to remove the interface URL, and then modify the business's private key configuration, and then impersonate the request in the browser
How to write a secure API interface (parameter encryption + timeout processing + private key verification +https)-continuation (with demo) (EXT)