Directory (toc)
Login to realize
After user B logs in, the browser saves cookies
Cookie content is as follows:
- key: xxx_V2
- value: 3001459%7C1636684996%7C7180720502%7Cb61a12ef865072964aa359e6a9ef2e0b1846dee9
The value can be divided into four period of values, separated by % 7 c, the Ascll code value is on behalf of the symbol “|”.
The four sections respectively represent userId, timestamp time, random number nonce, and sign obtained by encryption algorithm
Login code implementation details, cookie design
@global array $_SESSION * @param type $user_id */ public static function do_login($user_id) {global $_SESSION; $_SESSION["uid"] = $user_id; KZUser::add_auth_to_session($user_id); Unset ($_SESSION["login_try"]); unset($_SESSION["need_vcode"]); //send the cookie $login_time = time(); $nonce = mt_rand(1000000000, 9999999999); $cookie_params = array($user_id, $login_time, $nonce); $cookie_params[] = hash_hmac("sha1", implode("", $cookie_params), COOKIE_KEY, false); $domain = str_replace(".t1.com", DOMAIN_POSTFIX, COOKIE_DOMAIN); // SESSION_COOKIE_NAME=xxx_V2 setcookie(SESSION_COOKIE_NAME, implode("|", $cookie_params), $login_time + 604800, "/", $domain, false, true); }Copy the code
Above is the calculation of setcookie function concrete implementation.
$cookie_params[] = hash_hmac("sha1", implode("", $cookie_params), COOKIE_KEY, false);
Copy the code
The last value of the cookie, sign, will be encrypted through calculation, using SHA1 algorithm encryption calculation to get a hexadecimal string to get sign.
COOKIE_KEY is the encrypted key, which is the same as that configured on the gateway. The gateway will use the same encryption algorithm, encryption parameters and encryption key for encryption calculation. If the parameters are the same, the calculated sign value will be consistent with the cookie, indicating that it is a valid cookie.
setcookie(SESSION_COOKIE_NAME, implode("|", $cookie_params), $login_time + 604800, "/", $domain, false, true);
Copy the code
The array with “|” connection into a string that is to get in front of the four cookie value.
The gateway is introduced
What is an API gateway
API gateway is an architectural pattern that arose with the concept of microservices. Originally a huge All in one business system was split into many Microservice systems for independent maintenance and deployment. The changes brought about by service splitting are the doubling of API scale and the increasing difficulty of API management. Publishing and managing apis using API gateways is a growing trend.
Generally speaking, THE API gateway is a traffic entrance between external requests and internal services, realizing the protocol conversion, authentication, flow control, parameter verification, monitoring and other general functions of external requests.
Why you need a gateway
In the microservice architecture, a single application is divided into multiple microservices. If all the microservices are directly exposed to the outside world, various security problems are bound to occur.
If the client can directly send requests to each microservice, the main problems are as follows:
- Client requirements do not match the fine-grained apis exposed by each microservice.
- Each company may have Java, Python, and Go languages, and may use different protocols in different scenarios. Some services may use non-Web-friendly protocols, such as Thrift binary RPC, AMQP messaging protocol, or other protocols such as GRPC.
- The division of microservices may change over time and microservices are difficult to reconstruct. If two services are merged, or a service is split into two or more services, this kind of refactoring becomes very difficult.
- Different clients may require different data, such as Web,H5,APP,Android,IOS.
Gateway open source components are widely used in the industry, such as Zuul, SpringCloud Gateway, Kong, and Nginx.
From a technical standpoint, what is Kong?
This paragraph is taken from KONG’s official introduction document \
You’ve probably heard that Kong is based on Nginx, taking advantage of its stability and efficiency. But how exactly does this work? Rather, Kong is a Lua application that runs in Nginx and can be implemented through the Lua-Nginx module. Instead of compiling Nginx with this module, Kong distributes it with OpenResty, which already includes lua-nginx-Module. OpenResty is not an offshoot of Nginx, but a set of modules that extend its functionality. This sets the stage for a pluggable architecture that enables and executes Lua scripts (called “plug-ins”) at run time. Therefore, we consider Kong to be a good example of a microservices architecture: its core is database abstraction, routing, and plug-in management. Plug-ins can exist in a separate code base and can be injected anywhere in the request lifecycle in a few lines of code.
In short, Kong is Mashape’s open source high-performance high availability API gateway and API service management, a high availability service gateway written based on the Nginx_Lua module. Since Kong is based on Nginx, it can scale multiple Kong servers. Requests are evenly distributed to each Server through pre-configured load balancing configuration to cope with a large number of network requests.
Why use Kong
Among many API GATEWAY frameworks, Mashape’s open source high performance and high availability API GATEWAY and API service management layer — KONG (based on NGINX) is particularly prominent. It can extend existing functions through plug-ins. These plug-ins (written in Lua) are executed during the lifecycle of the API request response cycle. At the same time, KONG itself provides HTTP basic authentication, key authentication, CORS, TCP, UDP, file logging, API request traffic limiting, request forwarding, NGINX monitoring and other basic functions.
In addition to Kong’s basic gateway functions, Kong’s cloud native properties: platform-independent, Kong can run from bare to Kubernetes, is the reason we like, our services are all k8S deployment scheduling.
Some of the terms Kong often uses are:
- Client: a downstream client sends a request to the Kong proxy port.
- Upstream: refers to the API/ service (s) to which the client request is forwarded (s) following Kong.
- Service: As the name implies, a Service entity is an abstraction of an upstream Service. Examples of services include data transformation microservices, billing apis, and so on.
- Route: This refers to the Kong routing entity. A Route is an entry point into Kong and defines rules for requests to match, then routes to a given service.
- Plugin: Refers to Kong’s “plugins,” which are pieces of business logic that run during the agent’s life cycle. Plug-ins can be configured through the management API — either globally (all incoming traffic) or on specific routes and services.
The Kong gateway parses cookies
Kong Project introduction, traffic forwarding
This project is only authenticated and belongs to the Intranet gateway. Before that, traffic also passes through an external gateway, where flow control, request distribution, certificate configuration and other functions are provided. The Intranet gateway only performs authentication.
The project deployed online gateway and test environment gateway, and provided plugins plug-in authentication has authentication of APP end, C end and B end. Here I mainly talk about authentication of B end, and others are briefly introduced:
- Shop-resolve is mainly shop information authentication under the two environments of small program and H5, which is needed for an e-commerce project of the company.
- In IDK-client-type-resolve, access authentication is performed in small programs and H5 environments.
- There is nothing to say about the health-check. Is it necessary for the k8S health check
- The other three app-resolve, Buser-Reslove, and Cuser-resolve are app environment, B-end, and C-end authentication respectively
Kong. ymal is configured with many Service lines. For example, the kuaizhan.com cloud Service can be routed (www.kuaizhan.com, cloud.kuaizhan.com) and buser-resolve authentication plug-in is used in the configuration. Upstream (” name “) :
Upstream (k8S) : upstream (k8S) : upstream (K8S) : upstream (K8S) : upstream (K8S) : upstream (K8S) : upstream (K8S) : upstream
Authentication luA script
local ngx_re = require "ngx.re" local BasePlugin = require "kong.plugins.base_plugin" local string = require "resty.string" local BuserResolveHandler = BasePlugin:extend() function BuserResolveHandler:new() BuserResolveHandler.super.new(self, "buser-resolve") end function BuserResolveHandler:access(conf) BuserResolveHandler.super.access(self) local cookieName = "cookie_" .. "KUAIZHAN_V2" local kuaizhanV2 = ngx.var[cookieName] -- ngx.log(ngx.ERR, "kuaizhanV2", kuaizhanV2) local uid = 0 ngx.req.set_header("X-User-Id", Uid) / / cookie content 3001459% 7 7 c7180720502 c1636684996% % 7 cb61a12ef865072964aa359e6a9ef2e0b1846dee9 if xxx_V2 and xxx_V2 ~ = "Then local res, err = ngx_re.split(xxxV2, "%7C") if err then return end // 3001459,1636684996,7180720502, respectively, B61a12ef865072964aa359e6a9ef2e0b1846dee9 local userId, time, nonce, sign = res [1], the res [2], the res [3], the res [4] / /, according to the key time, signature, Local digest = ngx.hMAC_sha1 (conf.secret, userId.. time .. Nonce) local theSign = string.to_hex(digest) -- TODO plus expiration time If theSign == sign then uid = userId end ngx.log(ngx.ERR, "theSign:", theSign, "sign:", sign, "uid:", uid) end ngx.log(ngx.ERR, "get x-user-id:" .. // ngx.req.set_header(" x-user-id ", uid) end return BuserResolveHandlerCopy the code
The analysis process is as follows:
- Cookie content 3001459% c1636684996%7 July 7 cb61a12ef865072964aa359e6a9ef2e0b1846dee9 c7180720502%
- Parsed userId, time, nonce, sign, 3001459163684, 996718720, 502 respectively, b61a12ef865072964aa359e6a9ef2e0b1846dee9
- According to the key, user ID, time, random number, using hMAC_SHA1 algorithm, hexadecimal algorithm, get the summary signature, calculate the signature and cookie parsing to get whether sign is the same, then assign uid
- The nginx request header contains the X-user-ID, which is then forwarded to each K8S service.
Conf. secret Specifies the secret configured in conf.secret. If many lines of business share the same login, for example, many lines of business on the official website, the secret configuration is the same.
Service resolution request
In this way, the gateway layer is implemented in the header set userId information, to each business side directly write a parser to parse the request header userId;
Then write a custom annotation like @loginRequired with the variable BUser, which contains the parsed userId.
Finally, the annotation is applied to the Controller interface to complete the interception of the requested login information.
Because this implementation is too partial to the business, and relatively simple here will not stick to the specific code implementation.
Advantages and disadvantages of this scheme implementation
Advantages:
- Simple implementation, easy maintenance and easy to understand
- Unified network authentication and traffic distribution can be implemented
Single sign-on problem
Generally, an enterprise has only one domain name. Secondary domain names are used to distinguish different systems. For example, our main domain name is xxx.com, and another business line has a secondary domain name aaa.xxx.com. Now we want to log in on the official website, so we will log in on another business line. The implementation is as follows:
After login, you can set the Cookie domain to the top domain xxx.com so that all systems in the subdomain can access the cookies in the top domain. When we set cookies, we can only set the top field and our own field, not other fields. Therefore, the other line of business can directly access the login state of the top domain, and then parse the access request in Kong, and set the key to the same can be authenticated.
But single sign-on across multiple or top domains is not possible.
Login renewal problem
I don’t know if you have noticed that there is an expiration time after the first cookie screenshot. Since this type relies on cookies, it will be kicked off as soon as it expires and needs to log in again, which affects customer experience to some extent.
Nowadays, many applications use the Token + Redis solution to renew the login. For example, if you have logged in within 10 consecutive days, you do not need to log in again. The backend automatically renew the login, and those who have not logged in for more than 10 days are invalid and need to log in again.
However, the renewal service requires redis cost, which is a cost saving.
Cancellation of problem
The cancellation of this scheme is just a simple deletion of the cookie. If someone gets the cookie, it is still available, and the cookie will not be invalid within the validity period.
The token+ Redis scheme can make the real token invalid.
The above is all the content to share this article, I am “xiaolongfei” public number of the main small flying dragon, welcome to pay attention to my public number to view more past wonderful content, the original is not easy, if you have a harvest can point a like point in the number of encouragement to see the main bar ~ ~ ~
Note: Please refer to the official kong documentation for some professional explanations in this article