Spring Security 3 (iii) User data stored in the database

Source: Internet
Author: User
Tags stub

Oberzhang review:

in the previous chapter, we configured the user name, password, and user-corresponding roles in Applicationcontext-security.xml , which basically implemented the ability to control the user's access rights. But in real-world development, we can not hard code user information in the configuration file, usually we are stored in the data. At the same time we should encrypt the user's password to store.


Goal:

1. storing user information in a database

2. Encrypt the user's password


Detailed Operation:

1. Other codes refer to the code in the previous chapter. In this chapter, we first create a data table to record our user information. springsecurity provides a validation mechanism, first of all, we customize the Entity class to implement Userdetails, and to implement several methods of his interface, the following is the specific code:

@SuppressWarnings ("Serial") @Entity (name = "User") @Table (name = "UserInfo") public class User implements Userdetails {@i D @GeneratedValue (strategy = Generationtype.auto) @Column (name = "id", unique = true, Nullable = false) Private I    NT ID;    @Column (name = "username") private String username;    @Column (name = "password") private String password;    @Column (name = "role") private String role;    @Column (name = "Enabled") Private Boolean enabled = FALSE;    @Column (name = "Salt_value") private String salt_value;    public int getId () {return id;    } public void setId (int id) {this.id = ID;    } public void Setusername (String username) {this.username = username;    } public void SetPassword (String password) {this.password = password;    Public String Getrole () {return role;    public void Setrole (String role) {this.role = role; } @Override public collection<? Extends GrantedauthoritY> getauthorities () {list<grantedauthority> List = new arraylist<grantedauthority> ();        System.out.println ("User ' s role:" + getrole ());        List.add (New Simplegrantedauthority (Getrole ()));    return list;    } @Override Public String GetPassword () {return this.password;    } @Override Public String GetUserName () {//TODO auto-generated method stub return this.username;    } @Override public Boolean isaccountnonexpired () {//TODO modify return true as needed;    } @Override public Boolean isaccountnonlocked () {//TODO auto-generated method stub return true;     } @Override public Boolean iscredentialsnonexpired () {//TODO auto-generated method stub return true;    } @Override public Boolean isenabled () {//TODO auto-generated method stub return this.enabled;    The public void SetEnabled (Boolean enabled) {this.enabled = enabled;   } Public String Getsalt_value () {return salt_value;    } public void Setsalt_value (String salt_value) {this.salt_value = Salt_value; }}

First,the Getauthorities () method, we need to return the user's role collection, but because we are convenient, a user defines only one role. In actual development, we can change toa list and then add it to the corresponding collection.

There are a few @Override methods that are required to be implemented in the interface, because in springsecurity to determine if a user can log in, Whether there is permission to access certain resources is through these properties to judge, so we according to their own needs to carry out the return value. And each method name is already written to the meaning of the clear representation.


Once the 2.Entity is set up, we'll build our data. The code is posted directly here:

DROP TABLE IF EXISTS ' userinfo '; CREATE TABLE ' userinfo ' (  ' id ' int (one) not null auto_increment,  ' username ' varchar () DEFAULT NULL,  ' Password ' varchar (255) default NULL,  ' role ' varchar default NULL,  ' enabled ' tinyint (1) default NULL,  ' Salt_value ' varchar () default NULL,  PRIMARY KEY (' id ')) engine=innodb default Charset=utf8;


3.Spring security How do we verify our users? In our own way of thinking, it should be: Find out whether the user in our database -> verify user password -> other judgments -> If the user is logged in successfully. In this example, we have configured the access to the resource in the springsecurity configuration file, so we just need to find the user and return to the Springsecurity The processor, let him handle it himself. So we're going to implement the Springsecurity interface:

Public interface UserService extends userdetailsservice{} @Service (value = ' userservice ') public class Userserviceimpl Implements UserService {    @Autowired    private Userdao Userdao;    @Override public    userdetails loaduserbyusername (String username)            throws usernamenotfoundexception {        System.out.println ("Find the user name:" + username);        User user = Userdao.getuserbyusername (username);        System.out.println (user = = null);        if (user = = null) {            System.out.println ("username can ' t found");            throw new Usernamenotfoundexception ("Username not Found ...");        return user;    }}


4. to this, the basic has been done. Now we just need to modify the configuration file and tell Springsecurity to implement it in our own way, modifying the applicationcontext-security.xml:

<authentication-manager> <authentication-provider user-service-ref= "UserService" > <password-encoder ref= "Passwordencoder" > <salt-sourc E ref= "Saltsource"/> </password-encoder> </authentication-provider> </authenticatio n-manager> <!--password Salt, take username as salt-<!--Userpropertytouse: Mainly used to put our object into his method, remove the salt value by this property name--<        ; Beans:bean id= "Saltsource" class= "Org.springframework.security.authentication.dao.ReflectionSaltSource" > <beans:property name= "Userpropertytouse" value= "Salt_value" ></beans:property> </beans:bean> < !--SHA Encryption Class--<beans:bean id= "Passwordencoder" class= "Org.springframework.security.authentication.encodin G.shapasswordencoder "> </beans:bean> 

we do this by using the encryption method provided by Springsecurity is encrypted, and we increase the salt value in the password so that the hack fails.

Authentication-provider in user-service-ref, is the service class that we customized in the previous point . At the same time we provide encryption methods.


5. Here we have a problem, if we manually add data to the database, the password is plaintext, not encrypted. In order for us to successfully login, we designed a registered user's page to register the user. Registered Users page we have to play, the main data passed to the background include: User name, password, role. The main point is to look at how to encrypt the password:

/** * Injected two Tools class */@Resourceprivate Reflectionsaltsource Saltsource;                  @Resourceprivate Shapasswordencoder passwordencoder;/** * Registered user * @param user * @return */@RequestMapping ("/register") Public Modelandview Register (user user) {    user.setenabled (true);    Use the current time of the system as the Salt value    user.setsalt_value (system.currenttimemillis () + "");    Encrypt password: old password + salt value. The salt value is obtained from the user object, and we have written to find which property in the configuration    String password = Passwordencoder.encodepassword (User.getpassword (), Saltsource.getsalt (user));    User.setpassword (password);    if (userdao.adduser (user)) {            System.out.println ("register Success");    } else {        System.out.println (" Failed ");    }    return new Modelandview ("redirect:/login.jsp");}


6. OK, the user we registered successfully, you can jump directly to the login page, with just registered user name and password to log in, and to conduct a permission test.



This article is from the "Sg-yyz" blog, so be sure to keep this source http://sgyyz.blog.51cto.com/5069360/1409098

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.