Spring Security controls user information users encrypt cached user information

Source: Internet
Author: User
Tags md5 encryption

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:

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

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.

2. Salt-Value encryption

The above example in the real 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>

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.

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>    <jdbc-user-service data-source-ref=" DataSource "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:

class= "Org.springframework.security.core.userdetails.cache.EhCacheBasedUserCache" >    Class = "Org.springframework.cache.ehcache.EhCacheFactoryBean" >    <beans:property name= "CacheManager" ref= "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 = "        eternal" = "false"        timetoidleseconds= "        timetoliveseconds" = "        overflowtodisk" = "true"    />    <cache        Name= "Usercache"         maxelementsinmemory= "100"//memory holds up to 100 Objects         Eternal= "false"//not permanent cache         Timetoidleseconds= "600"//maximum idle time is 600s        timetoliveseconds= "3600"//maximum active time is 3600s         Overflowtodisk= "true"//If a Memory object overflow is saved to disk    /></ehcache>

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.

Note

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.

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.

Spring Security controls user information users encrypt cached 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.