6th Chapter Control User Information

Source: Internet
Author: User

Reprint: Http://www.mossle.com/docs/auth/html/ch006-user-info.html the 6th Chapter controls user Information

Let us study some of the functions related to user information, including the user password encryption, cache user information, to obtain the system currently logged on users, access to all the rights of the login user.

6.1. MD5 Encryption

In any formal enterprise application, no plaintext is used in the database to store passwords, and in previous chapters we did not encrypt the user passwords in the database for convenience, which is extremely naïve in practice. You can imagine, as long as someone into the database can see everyone's password, this is a terrible thing, so we must at least encrypt the password, so that even if the database is compromised, can also guarantee the security of the user password.

The most common method is to use the MD5 algorithm to digest encryption of the password, which is a single encryption method, can not be reversed through the encrypted results of the original password plaintext.

First we need to encrypt the original saved password in the database using MD5:

Insert into users values (' admin ', '21232f297a57a5a743894a0e4a801fc3 ', TRUE) insert into users values (' user ', '  Ee11cbb19052e40b07aac0ca060c23ee ', TRUE)         

Now the password part has been unrecognizable, even if someone broke the database, get this "garbled" can not log on the system to steal customer information.

Next in order for spring security to support MD5 encryption, we need to modify the configuration file.

<authentication-provider>    <password-encoder hash= "MD5"/>    <jdbc-user-service data-source-ref= "DataSource"/></authentication-provider>        

The new yellow part of the code above will enable the MD5 algorithm. When the user logs in, the password entered is clear text and needs to be converted to MD5 form using Password-encoder, and then compared to the encrypted password in the database.

These configurations have no effect on ordinary customers, they only need to enter their own passwords, and Spring security automatically calculates the results to match the information stored in the database to determine whether the user can log in.

In this way, we have added a single line of configuration, which brings the function of password encryption to the system.

6.2. Salt-Value encryption

In fact, the above example in the actual use of the existence of a very small problem. Although the MD5 algorithm is irreversible, because it is unique to the result of the same string calculation, some people may use a "dictionary attack" approach to compromise the MD5 encrypted system [5]. Although this is a brute force decryption, it is very effective, because most of the system user passwords are not back very long.

In fact, most systems use admin as the default administrator login password, so when we see "21232F297A57A5A743894A0E4A801FC3" in the database, we can realize the password used by the Admin user. As a result, MD5 does not work well when dealing with this common string.

To solve this problem, we can use the salt value to encrypt "Salt-source".

To modify a configuration file:

<authentication-provider>    <password-encoder hash= "MD5" >        <salt-source user-property= "username"/>    </password-encoder>    <jdbc-user-service data-source-ref= " DataSource "/></authentication-provider>          

Salt-source is added under Password-encoder, and username is specified as the salt value.

The principle of salt is very simple, that is, the combination of the content of the password and salt, and then use MD5 to calculate the combined content, so that, even if the password is a very common string, coupled with the user name, the last calculated MD5 value is not so easy to guess. Because the attacker does not know the value of the salt value, it is difficult to reverse the original password.

We use each user's username as the salt value, and then the cipher part of the database becomes this:

Insert into users values (' admin ', 'ceb4f32325eda6142bd65215f4c0f371 ', TRUE) insert into users values (' user ', '  47a733d60998c719cf3526ae7d106d13 ', TRUE)         
6.3. User Information caching

User information in the system does not change frequently, so using the cache becomes a good choice for improving performance. Spring Security's built-in cache implementation is based on Ehcache, and in order to enable caching, we want to add relevant content to the configuration file.

<authentication-provider>    <password-encoder hash= "MD5" >        <salt-source user-property= " Username "/>    </password-encoder>    cache-ref=" Usercache "/></authentication-provider >        

We added a reference to Usercache in the Jdbc-user-service section, which will use this bean as the implementation of the user rights cache. The configuration for Usercache is as follows:

<beans:bean id= "Usercache" class= "Org.springframework.security.core.userdetails.cache.EhCacheBasedUserCache" >    <beans:property name= "cache" ref= "Userehcache"/></beans:bean><beans:bean id= "UserEhCache" class= "Org.springframework.cache.ehcache.EhCacheFactoryBean" >    <beans:property name= "CacheManager" ref= "CacheManager"/>    <beans:property name= "CacheName" value= "Usercache"/></beans:bean><beans: Bean id= "CacheManager" class= "Org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>        

Ehcachebasedusercache is a cache implementation built into spring security that will provide caching capabilities for Jdbc-user-service. The Userehcache referenced by it comes from the Ehcachefactorybean and Ehcachemanagerfactorybean provided by spring, and the cache configuration for Usercache is placed in Ehcache.xml:

<ehcache>    <diskstore path= "Java.io.tmpdir"/>    <defaultcache        maxelementsinmemory= "1000 "        eternal=" false "        timetoidleseconds=" "timetoliveseconds=" "        overflowtodisk=" true "    / >    <cache        name= "Usercache"        maxelementsinmemory= "100"
        Eternal= "false"
        timetoidleseconds= "600"
        timetoliveseconds= "3600"
        Overflowtodisk= "true"
    /></ehcache>

A maximum of 100 objects are stored in memory.

is not a permanent cache.

Maximum idle time is 600 seconds.

The maximum active time is 3,600 seconds.

If the memory object overflows, it is saved to disk.

If you want to learn more about Ehcache, you can visit its official website, http://ehcache.sf.net/.

In this way, we set the user rights information cache, when a user multiple access to the application, do not need to access the database every time, Ehcache will cache the corresponding information, which will greatly improve the corresponding speed of the system, but also to avoid the database to meet the risk of excessive.

Attention

Cache-ref Hidden a trap, if you do not look at the code, we may mistakenly think that Cache-ref will set the corresponding Usercache in Jdbcuserdetailsmanager, The user cache can then be automatically maintained as long as the methods in Jdbcuserdetailsmanager are executed directly.

Unfortunately, Cache-ref is actually based on Jdbcuserdetailsmanager, generating a cachinguserservice, This cacheduserdetailsservice intercepts the Loaduserbyusername () method, which implements the caching function for reading user information. The Usercache we quoted in Cache-ref is actually placed in Cacheuserdetailsservice, not in the original Jdbcuserdetailsmanager, This causes the user cache operation to be invalidated in Jdbcuserdetailsmanager.

6.4. Get Current User information

If you just want to display the current logged-on user name from the page, you can use the taglib provided by spring security directly.

<%@ taglib prefix= "SEC" uri= "Http://www.springframework.org/security/tags"%><div>username: <sec: Authentication property= "Name"/></div>        

If you want to get the object for the current logged-on user in the program.

Userdetails userdetails = (userdetails) securitycontextholder.getcontext ()    . Getauthentication ()    . Getprincipal ();        

If you want to get all the permissions that the current logged-on user has.

Collection<grantedauthority> authorities = (collection<grantedauthority>) userDetails.getAuthorities () ;;        

We'll go through the details of how userdetails is put into Secuirtycontext and the theadlocal mode used by spring security. Here we have learned how to get information about the current logged-in user.


[5] The so-called dictionary attacks, refers to the use of a large number of commonly used strings MD5 encryption, form a dictionary library, and then a section of the MD5 calculus obtained by the unknown string, in the dictionary library search, when the matching results, you can obtain the corresponding encryption string content.

6th Chapter Control User Information

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.