Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Server \ Cache implementation APP interacts with the server-side interface control Session     - Ubuntu 14.04 next upgrade to GNOME 3.12 (Linux)

- Based Corosync + Pacemaker + DRBD + LNMP Web server to achieve high availability cluster (Server)

- Install minimize RHEL / CentOS 7 things to do (Linux)

- How to install Linux Kernel 4.4 on Ubuntu (Linux)

- Simple comparison of MySQL and Oracle in a sql analytical details (Database)

- On the design of Oracle database backup (Database)

- Ubuntu 14.04 Install WordPress on Nginx (Server)

- In-depth understanding of PHP ini configuration (Server)

- Ubuntu install VMware Workstation 11 tutorials at 14.04 / 14.10 (Linux)

- Slow update statement Performance Analysis (Database)

- Let MySQL 5.6 support Emoji expression (Database)

- Create the container and run the application Docker (Server)

- Ubuntu Tutorial - Manually install Oracle Java JDK 8 (Linux)

- OpenWRT environment to build (Linux)

- MySQL flip-flop (Database)

- Oracle Database Restore (Database)

- Ubuntu 14.10 / 14.04 / 12.04 installation GNOME Pie 0.5.6 (Linux)

- Use Docker containers (Linux)

- How to create an alternative Android / iOS connected wireless hotspot AP in Ubuntu 15.04 (Linux)

- Automated Password Generator: Linux under a special password generator (Linux)

 
         
  Cache implementation APP interacts with the server-side interface control Session
     
  Add Date : 2018-11-21      
         
         
         
  With the traditional B / S mode of Web systems, interactive interface between the mobile terminal APP and the server is usually C / S mode, in which case if it comes to user logon, then it is not as dependent on the Web, like Web container system Session management, because the APP will request that every time the server creates a new Session. While others relate to user privacy or financial transactions of the interface must also confirm the legitimacy of the current user logged on, if there is no login or login has expired you can not conduct such operations.
I have seen a kind of "lazy" approach, that is, after the user first login, the user ID stored in the local store, and then interact with the server's user interfaces are identified by a user ID.

This approach has two main drawbacks:

As long as the user ID stored locally is not deleted, you can always access the above interfaces, you need to re-login, unless the increase is valid judgment or the user voluntary withdrawal;
Interface security is weak, because the user ID corresponding to the database that uniquely identifies the user, as long as others can get a fake user ID or user ID, you can use the user interface to more illegal operation.
In summary consideration, you can use the cache on the server side analog Session management mechanism to solve this problem, of course, this is currently a relatively simple effective solution APP User Session program I know. If any friends have other good program, please leave a message in the following exchange.

Caching framework here is Ehcache, Download http://www.ehcache.org/downloads/, of course, you can also use Memcached or other. The reason to use Ehcache framework, on the one hand because it is lightweight, fast, and simple integration, on the other hand it is also the default Hibernate CacheProvider, has been integrated for the Hibernate project do not need to add additional Ehcache the jar package.

With Ehcache, then you must add the appropriate configuration, and configuration information in the Spring configuration file as follows:

 1 < ! - Configuration Cache Manager plant ->
 2 < bean id = "cacheManager" class = "org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
 3 < property name = "configLocation" value = "classpath: ehcache.xml" />
 4 < property name = "shared" value = "true" />
 5 < / bean>
 6 < -! Cache factory configuration, the cache name myCache ->
 7 < bean id = "ehcache" class = "org.springframework.cache.ehcache.EhCacheFactoryBean">
 8 < property name = "cacheName" value = "myCache" />
 9 < property name = "cacheManager" ref = "cacheManager" />
10 < / bean>
In addition, Ehcache profile ehcache.xml in the configuration is as follows:

 1 < ? Xml version = "1.0" encoding = "gbk"?>
 2 < ehcache xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
 3 xsi: noNamespaceSchemaLocation = "ehcache.xsd">
 4 < diskStore path = "java.io.tmpdir" />
 5
 6 < ! - Configure a default cache, must ->
 7 < defaultCache maxElementsInMemory = "10000" eternal = "false" timeToIdleSeconds = "30" timeToLiveSeconds = "30" overflowToDisk = "false" />
 8
 ! 9 < - configure custom caching maxElementsInMemory: cache allows you to create the maximum number of objects eternal: the cache object is permanent, if it is, the timeout setting is ignored, the object never expires.
10 timeToIdleSeconds: passivation time cached data, that is, before the demise of an element, the maximum value of the interval time of two visits, which can only be effective when the element is not a permanent resident,
11 If the value is 0 means that elements can pause infinitely long time. timeToLiveSeconds: survival time data cache, which is an element interval value from the maximum time to build demise,
12 This can only be effective when the element is not a permanent resident, if the value is 0 means that elements can pause infinitely long time. overflowToDisk: insufficient memory, disk cache is enabled. memoryStoreEvictionPolicy: caching algorithm eliminated after full. ->
13 < cache name = "myCache" maxElementsInMemory = "10000" eternal = "true" overflowToDisk = "true" memoryStoreEvictionPolicy = "LFU" />
14 < / ehcache>
Once configured Ehcache, can be injected directly into the cache instance through the @Autowired or @Resource. Sample code is as follows:

 1 @Component
 2 public class Memory {
 3 @Autowired
 4 private Cache ehcache; // Note that the introduction of Cache is net.sf.ehcache.Cache
 5
 6 public void setValue (String key, String value) {
 7 ehcache.put (new Element (key, value));
 8 }
 9
10 public Object getValue (String key) {
11 Element element = ehcache.get (key);
12 return element != null ? element.getValue (): Null;
13}
14}
The cache is ready, the next step is simulated users Session, the idea is to achieve this:

After the user logs in successfully, the server generates a token Token according to certain rules, Token is variable, it can be fixed (will be described later);
The Token as a key, user information as a value into the cache, set sometimes long (over 30 minutes without access to fail);
The Token returned to the terminal APP, APP saved to a local store to take this parameter request interface;
By interceptor to intercept all the interfaces related to user privacy and security aspects of the verification request Token parameters and check the legality of the cache has expired;
Once validated, save the Token value to the thread storage for the current thread operations can be indexed by the user currently logged Token directly from the cache.
In summary, APP side need to do is log on and get the Token is stored from the server to bring privacy-related user when accessing the Token interface as its identity. The server side to do is to intercept user privacy related Interface Authentication Token and login information, verify Token will be saved to the thread variable, then you can remove the Token in other operations and to obtain current user information from the cache. Such APP not need to know the user ID, it's just to get a identity, and this identity is variable, according to the identification server can know which user is to be operated.

For Token whether variable, differ on the details of treatment, the effect is not the same.

Token fixed situation: the server side generated Token username and password together MD5 encryption, namely MD5 (username + password). Thus for the same user, every time you log Token is the same, the user can log in multiple clients share a Session, when a user password change requires users to log in again;
Token variable situation: the server side generated Token user name, password, and current timestamp together MD5 encryption, namely MD5 (username + password + timestamp). Thus for the same user, each Token logon is not the same, and then clearing the cache on first login, you can achieve unique effects logged in user.
In order to ensure that a user with only one in the cache logon information, the server after generating the Token, you can then separate the user names MD5 as Seed, namely MD5 (username). Then Seed as a key, Token save it as a value to the cache, so even Token vary, but each user's Seed is fixed, it can be indexed by Seed Token, login information again by clearing the Token avoid repeated logon cache stored in too many invalid login information.

Token-based Session Control part of the code is as follows:

 1 @Component
 2 public class Memory {
 3
 4 @Autowired
 5 private Cache ehcache;
 6
 7 / **
 8 * Close the Cache Manager
 9 */
10 @PreDestroy
11 protected void shutdown () {
12 if (ehcache! = Null) {
13 ehcache.getCacheManager (). shutdown ();
14}
15 }
16
17 / **
18 * save the login information for the current user
19 *
20 * @param loginUser
21 */
22 public void saveLoginUser (LoginUser loginUser) {
23 // token and generate seed values
24 String seed = MD5Util.getMD5Code (loginUser.getUsername ());
25 String token = TokenProcessor.getInstance (). generateToken (seed, true);
26 // Save the token to the login users
27 loginUser.setToken (token);
28 // clear the login information before
29 clearLoginInfoBySeed (seed);
30 // save the new token and login information
31 String timeout = getSystemValue (SystemParam.TOKEN_TIMEOUT);
32 int ttiExpiry = NumberUtils.toInt (timeout) * 60; // convert seconds
33 ehcache.put (new Element (seed, token, false, ttiExpiry, 0));
34 ehcache.put (new Element (token, loginUser, false, ttiExpiry, 0));
35}
36
37 / **
38 * Get the current thread user information
39 *
40 * @return
41 * /
42 public LoginUser currentLoginUser () {
43 Element element = ehcache.get (ThreadTokenHolder.getToken ());
44 return element == null null: (LoginUser) element.getValue ();?
45 }
46
47 / **
48 * According token check whether the user login
49 *
50 * @param token
51 * @return
52 * /
53 public boolean checkLoginInfo (String token) {
54 Element element = ehcache.get (token);
55 return element != null && (LoginUser) element.getValue () != null;
56}
57
58 / **
59 * Clear Login Information
60 * /
61 public void clearLoginInfo () {
62 LoginUser loginUser = currentLoginUser ();
63 if (loginUser! = Null) {
64 // generate seed according to login user name, and then clear the login information
65 String seed = MD5Util.getMD5Code (loginUser.getUsername ());
66 clearLoginInfoBySeed (seed);
67}
68}
69
70 / **
71 * According seed Clear Login Information
72 *
73 * @param seed
74 * /
75 public void clearLoginInfoBySeed (String seed) {
76 //According sid find the corresponding token
77 Element element = ehcache.get (seed);
78 if (element! = Null) {
79 // login token emptied before under
80 ehcache.remove (seed);
81 ehcache.remove (element.getValue ());
82}
83}
84}
Token interceptor part of the code is as follows:

 1 public class TokenInterceptor extends HandlerInterceptorAdapter {
 2 @Autowired
 3 private Memory memory;
 4
 5 private List < String> allowList; the release of the list of URL //
 6
 7 private static final PathMatcher PATH_MATCHER = new AntPathMatcher ();
 8
 9 @Override
10 public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
11 // determine whether the operation to release the requested URI, if it does not allow verification request token information
12 if (! CheckAllowAccess (request.getRequestURI ())) {
13 // token value to check whether the request is empty
14 String token = getTokenFromRequest (request);
15 response.setContentType (MediaType.APPLICATION_JSON_VALUE);
16 response.setCharacterEncoding ( "UTF-8");
17 response.setHeader ( "Cache-Control", "no-cache, must-revalidate");
18 if (StringUtils.isEmpty (token)) {
19 response.getWriter () write ( "Token can not be blank");
20 response.getWriter () close ().;
21 return false;
22 }
23 if (! Memory.checkLoginInfo (token)) {
24 response.getWriter () write ( "Session expired, please login again");
25 response.getWriter () close ().;
26 return false;
27}
28 ThreadTokenHolder.setToken (token); // Save the current token, for the Controller layer to obtain user logon information
29}
30 return super.preHandle (request, response, handler);
31}
32
33 / **
34 *Check URI whether to release
35 *
36 * @param URI
37 * @return return test results
38 * /
39 private boolean checkAllowAccess (String URI) {
40 if (! URI.startsWith ( "/")) {
41 URI = "/" + URI;
42}
43 for (String allow: allowList) {
44 if (PATH_MATCHER.match (allow, URI)) {
45 return true;
46}
47}
48 return false;
49}
50
51 / **
52 * Get the value from the token request information
53 *
54 * @param request
55 * @return token value
56 * /
57 private String getTokenFromRequest (HttpServletRequest request) {
58 // get default value from the header in the token
59 String token = request.getHeader (Constants.TOKEN);
60 if (StringUtils.isEmpty (token)) {
61 // Get token value from the request information
62 token = request.getParameter (Constants.TOKEN);
63}
64 return token;
65}
66
67 public List < String> getAllowList () {
68 return allowList;
69}
70
71 public void setAllowList (List < String> allowList) {
72 this.allowList = allowList;
73}
74}
Here, has been to ensure a certain degree of legitimacy of interface requests, and will not be so easy to let others forge user information, even if others through illegal means to get the Token is only temporary, and when the cache invalidation or after you log in as Token invalid. If the server interface security requirements are higher, it can be replaced with SSL protocol to prevent the request from being intercepted.
     
         
         
         
  More:      
 
- Java input and output common class Scanner (Programming)
- Android developers learning Adapter (data adapter) (Programming)
- Java Foundation - implicit conversion vs cast (Programming)
- Hyper-V virtual hard disk how to copy files to and attached to the virtual machine (Linux)
- Install minimize RHEL / CentOS 7 some things need to do (Linux)
- 10046 trace only open for a particular SQL statement (Database)
- Zabbix configuration of SNMP (Server)
- Shell Programming Regular Expressions (Programming)
- Linux dd command make U disk boot disk (Linux)
- Recovery from MySQL master data consistency summary (Database)
- Using Lua implement various operations list (Programming)
- Install Java 8 on Ubuntu using PPA (Linux)
- Bash common several configuration files (Linux)
- Snapshot DataGuard (Database)
- Linux System Getting Started Learning: From VirtualBox from the client host access NAT (Linux)
- Java implementation chain store binary search tree (recursive method) (Programming)
- Ubuntu 14.04 kernel after the restart boot black screen to solve (Linux)
- Linux installation JDK1.6 rpm.bin assembly (Linux)
- CentOS 7 How to install MySQL Server (Database)
- Java to create a table in the database SYBase (Database)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.