sign in
A, Session across domains
The so-called cross-domain Session Session is to abandon the system provides, and the use of mechanisms similar to the Session custom to hold a solution to the client's data.
Such as: cross-domain transfer is achieved by providing the cookie the cookie domain. A custom passed session_id in a cookie. Session_id This is the only mark of the client. This will mark a key, the client will need to save the data as a value, save (or save NoSQL database stored) on the server. This mechanism is Session of cross-domain resolved.
Two, Spring Session Sharing
spring is spring-session technology to provide solutions for the processing cluster session sharing. spring-session session technique is to save the user data to a three storage containers, such as: mysql, redis like.
Spring-session technology to solve the multi-server cluster under the same domain session sharing problem. It not solves cross-domain session sharing problem.
Three, Nginx Session Sharing
ip_hash nginx art in a request can be directed to the same ip rear end, a client in this way and a rear end of the ip can establish a solid session, ip_hash configuration is defined in the upstream , as follows:
upstream nginx.example.com { server 127.0.0.1:8080; server 127.0.0.1:808; ip_hash; } server { listen 80; location / { proxy_pass http://nginx.example.com; proxy_set_header Host $http_host; proxy_set_header Cookie $http_cookie; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; client_max_body_size 100m; } }
nginx is not the most front-end server. ip_hash is easy to understand, but because only this factor can be assigned back-end ip, therefore ip_hash is flawed, can not be used in some cases:
ip_hash requirements nginx must be the most front-end server, otherwise nginx not correct ip, can not be based on ip for hash. For example, using squid for the most front-end, you can only get ip address of the server nginx squid when taking ip, use this address to make sure the shunt is garbled.
Nginx load balancing backend there otherwise.
If there are other back-end nginx load balancing, and shunt the request in another way, then the request of a client certainly can not locate the application server on the same session.
Four, Token mechanism
1. Traditional authentication
HTTP is a stateless protocol, that is, it does not know who is accessing the application. Here we put the user as a client, the client uses the user name as well as password authentication, but the next time the client sends a request again when then have to verify.
The solution is that when the user requests a login, if there is no problem, we generated a record on the server side, this record where you can explain who the user is about to log, and then send the ID number of records to put the client, after the client receives a Cookie, the service again next time the user sends a request to store the ID number, you can take the Cookie, so the server will verify the information in a Cookie this, see if you can in the service here ends the corresponding record is found, and if so, indicating the user has been authenticated, the user put the requested data is returned to the client.
Session is said above, we need to generate a user is logged on the server to store Session, the Session may be stored in memory, disk, or database. We may need to end the regular service to clear expired Session.
This certification question that arises is:
Seesion: Each time a user initiates an authentication request, the server needs to create a record to store information. As more and more users send requests, memory overhead will continue to increase.
Scalability: use Seesion store login information in the server's memory, accompanied by the scalability issues.
CORS (Cross-Origin Resource Sharing): When we need to make use of the data across multiple mobile devices, cross-domain resource sharing will be a headache for people. Grab resources in another domain using Ajax, it is prohibited request may occur.
CSRF (cross-site request forgery): user when accessing the bank's website, they are vulnerable to cross-site request forgery attacks, and can be exploited their access to other sites.
Among these problems, scalability is the most prominent. Therefore, we need to seek a more effective method.
2. Token Authentication
Use the Token-based authentication methods, logon recorded in the server does not need to store the user. Probably the process is this:
The client uses the user name and password to log requests
Server receives a request to verify the user name and password
After successful authentication, the server will issue a Token, then the Token is sent to the client
After receiving the client Token it can be stored, such as on the inside or Local Storage in Cookie
Every time a client requests a resource to the server needs with the server issued Token
Data server receives the request, and then to verify that the client requests inside with the Token, if authentication is successful, it is returned to the client's request
The advantage of using Token validation:
Stateless, scalable
Tokens stored in the client is stateless, and can be extended. Based on this storage state and a non-Session information, the load balancer is able to load user information from a service transmitted on another server.
safety
Sending the request token is no longer possible to prevent the transmission cookie CSRF (cross-site request forgery). Even if the client uses a cookie to store token, cookie store is only a mechanism and not for certification. The information is not stored in the Session, so that we have less of session operation.
Five, JSON Web Token (JWT) mechanism
JWT is a compact and self-contained, multi-pass technique for JSON object. Data transfer can use digital signatures to increase their security line. HMAC cryptographic algorithm may be used or RSA public / private key encryption.
Compact: the data is small, by URL, POST parameters, transmission request header. Small and the data representative of transmission speed.
Self comprising: a payload data block used to record user data privacy and not necessary, it can effectively reduce the number of database access and improve code performance.
JWT typically used to handle user authentication or data exchange.
User Authentication: Once the user logs on, every subsequent request will include JWT, allowing users to access the token allows routing, services and resources. Single sign-on is widely used today JWT's a feature, because the cost is small and can easily use across different domains.
Data exchange: JWT is a very convenient multi-carrier data transmission, because it can be used before the data to ensure the validity and security of the data.
1. JWT data structure
JWT data structures are: ABC. '' To separate the three points by the character data section.
A - header header
B - payload (payload?)
C - Signature Signature
1.1 header
Data structures: { "alg": "encryption algorithm name", "typ": "JWT"}
alg content encryption algorithm is defined as: HMAC SHA256 or RSA
typ is a token type, there is a fixed JWT.
1.2 payload
Usually the payload data block for recording entity (usually a user information) or other data. Is divided into three parts, namely: the registered information (registered claims), public data (public claims), private data (private claims).
payload commonly Offers: iss (issuer), exp (expiration time), sub (theme), aud (the audience) and so on . Previously cited are the registered information.
Discloses a data portion increase generally defined in JWT registry. Avoid conflict and registered information.
Private data and public data can be arbitrarily defined by the programmer.
Note: Even if there JWT signature encryption mechanism, but the payload content is expressly records unless the record is encrypted data, or do not rule out the possibility of leakage of private data. It does not recommend any sensitive data recorded in the payload.
1.3 Signature
Signature information. This is the information supplied by the developer. Server authentication data is valid safety standard delivery. JWT prior to generating the final data. First using an encryption algorithm defined in the header, the payload header and encrypted, using the connection points. Such as: head encrypted payload encrypted. Re-use the same encryption algorithm, the signature data and the encrypted information is encrypted. To get the final result.
2. JWT execution process
Sixth, based on a single point of login mechanism JWT
1. Implement
Refer to code
2. Note
When using JWT achieve single sign-on, note token timeliness. token data token is stored in the client, if permanent, there is likely to be hijacked. token in the design, it can be considered one-off or a period of time effective. If long effective, we need to consider the need to refresh token valid question.
3. token save location
JWT using technology generated token, the client may consider when saving a cookie or localStorage. cookie saving mode, you can achieve cross-domain data transfer. localStorage is the private domain of local storage and can not achieve cross-domain.
4. webstorage
webstorage save data capacity of 5M. And only storing string data.
webstorage into localStorage and sessionStorage.
localStorage life cycle is permanent, after closing the page or browser data in localStorage will not disappear. localStorage unless the initiative to remove data, otherwise the data will never disappear.
sessionStorage local storage unit is session related, is only effective in the life cycle in the current session. sessionStorage introduces the concept of a "browser window", sessionStorage is homologous window is always present in the data. As long as the browser window is not closed, even if refresh the page or go to another page homology, the data still exists. But sessionStorage will be destroyed after you close the browser window. Meanwhile a separate window open with the same page, sessionStorage is not the same.
Seven, Restful interface design
Brief 1. Rest
REST (English: Representational State Transfer, referred to as REST) architectural style describes a network system, such as a web application. It first appeared in 2000, Roy Fielding's doctoral thesis, he is one of the principal authors of the HTTP specification. In the current three major Web service interaction scheme, REST compared to SOAP (Simple Object Access protocol, Simple Object Access Protocol) and XML-RPC is more straightforward, either processed or URL for Payload encoding, REST are tend to design and implement a more simple and lightweight way. It is noteworthy that REST does not have a clear standard, but rather is a design style.
2. Restful Brief
Corresponding Chinese style is rest; Restful web service is a common application of rest, the rest is in compliance with the style of web services; rest-style web service is a ROA (The Resource-Oriented Architecture) (resource-oriented architecture ).
3. Restful properties
3.1 ordinary architecture
Every interface or address of the request, are doing described, for example, when queried by the query, the new time with the save. Such as:
http://127.0.0.1/user/query/1 GET queries the user data based on user id
http://127.0.0.1/user/save POST new users
3.2 Restful architecture
Use get request is to query using post request, is the new request, the intention clear, there is no need to do description, which is restful.
http://127.0.0.1/user/1 GET queries the user data based on user id
http://127.0.0.1/user POST new users
3.3 Restful operation
HTTP method |
Resource operation |
Idempotence |
Is it safe |
GET |
Inquire |
Yes |
Yes |
POST |
New |
no |
no |
PUT |
modify |
Yes |
no |
DELETE |
delete |
Yes |
no |
Idempotence: many visits, the result is the same as the state of the resource
Security: access to state whether it will change the server resources
3.4 Response Status Code
coding |
HTTP method |
In response body content |
description |
200 |
get/put |
Resource Data |
Successful operation |
201 |
post |
source data |
Creating success |
202 |
post/put/delete |
no |
Request has been accepted |
204 |
delete/put |
no |
Request has been processed, no data is returned |
301 |
get |
link link |
Resources have been removed |
303 |
get |
link |
Redirect |
304 |
get |
no |
Resource has not been modified |
400 |
get/post/put/delete |
Error message |
Parameter error (missing, malformed, etc.) |
401 |
get/post/put/delete |
Error message |
unauthorized |
403 |
get/post/put/delete |
Error message |
Access is limited, the license expires |
404 |
get/post/put/delete |
Error message |
Resources, services not found |
405 |
get/post/put/delete |
Error message |
Allowed HTTP methods |
409 |
get/post/put/delete |
Error message |
Resource conflict or resource is locked |
415 |
get/post/put/delete |
Error message |
Unsupported data types or media types |
429 |
get/post/put/delete |
Error message |
Too many requests is limited |
500 |
get/post/put/delete |
Error message |
system error |
501 |
get/post/put/delete |
Error message |
The interface is not implemented |
Use Example 4. SpringMVC Restful
Refer to code
Eight, the interface security mechanisms
1. DES encryption
2. AES encryption