API Security Design (1)

Source: Internet
Author: User
Tags sha1

1. Introduction to API

This time with the external company, has been writing external API interface. The API interface provided is based on the HTTP protocol and is stateless. The authentication information must be brought on each request. The background service verifies the identity information.
API authentication based on the HTTP protocol there are many ways, there are HTTP basic,http Digest,api Key,oauth,jwk, and so on, I only talk about the project based on the API KEY check.

2. API KEY

API interface through the request header (header) passed token (authorization token) for identity authentication and authentication, the system will verify the validity and timeliness of tokens.
API key is a user authentication after the server to assign an API key to the client, similar to: Http://test/api/package/create,
The generated tokens are placed on the head for transmission.

The general processing flow is as follows: A simple design example is as follows:

3, the client generates tokens

Calculate the PHP reference code for sign and token:
Design ideas:
USER_ID: The ID of the authorized customer;
App_key: The private key obtained after the API authorization is opened;
TS: The timestamp at the time the request was initiated, exactly to the second, this value is the same as the server timestamp when the request was received, the value deviation (positive or negative) more than 1200 seconds (20 minutes), the request is rejected, requesting the caller to regenerate;
Token (please use CCT +08:00 China Beijing Time);
Sign: The signature string, the key value of the input parameter is sorted in ascending order, converted into a string such as k1=v1&k2=v2, then splicing timestamp and App_key, and finally SHA1 confused;

function getToken($inputArr){    //当前unix时间戳    $userId = ‘3322991‘;    $appKey = ‘abc123‘;    $ts = time();    $sign = get_sign($inputArr, $ts, $appKey);    $token = base64_encode($userId . ‘,‘ . $ts . ‘,‘ . $sign);    return $token;}function getSign($inputArr, $ts, $appKey){    ksort($inputArr);    $inputStr = urlencode(http_build_query($inputArr));    $sign = sha1($inputStr . $ts . $appKey);    return $sign;}
4, the service side analysis token

The main idea of parsing tokens on the backend server is:
1, get the token parameters from header headers,
2, get user_id, TS and sign according to token,
3, and then according to USER_ID, TS and request parameters are newly generated signature sign;
4, check whether the App_key is legal, check the timeliness of TS, verify the new signature signed sign and signed sign is consistent.

    /** * Parse Token * @param $token * @param array $INPUTARR * @return Array */function Dectoken ($to        Ken, $INPUTARR = []) {$tokenInfo = Base64_decode ($token);        $tokenInfo = Explode (', ', $tokenInfo);        if (count ($tokenInfo)! = 3) {Error::trigger (' token information error ');        } list ($userId, $time, $sign) = $tokenInfo; Log::info ("Check token params,userid:{$userId},time: {$time},sign:{$sign},inputarr:".                Json_encode ($INPUTARR)); Time validity Check if (ABS (Times ()-$time) > \app::getconfig (' api_token_expire_time ')) {Error::trigger (Error        :: Err_param_token_time);        }//Sign $TOKENOBJ = new Token ();                Get user AppKey information, according to the actual project generated App_key rules $appKey = ' ***************** ';                $generateSign = $this->getsign ($INPUTARR, $time, $appKey);        Token $newToken generated by the checksum parameter = $this->gettoken ($INPUTARR, $userId, $appKey, $time); Log:: Info ("token:{$token},newtoken:".        Json_encode ($newToken)); Log::info ("sign:{$sign},newsign:".                Json_encode ($generateSign));        if ($sign!== $generateSign) {Error::trigger (error::err_param_token_sign);        } log::info (' token decoded successfully ');    return $appKey; }

API Security Design (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.