Previous post: Spring Security 4 integrated Hibernate bcrypt password encryption (with source)
Original address: http://websystique.com/spring-security/spring-security-4-remember-me-example-with-hibernate/
"Related translated articles in this series, click on Spring Security 4" in category
This tutorial will show you persistent login validation using spring Security 4 and hibernate.
In persistent login verification, the app remembers the user characteristics through the session.
Generally, at the login screen, when you provide "Remember password" support, the app will send a cookie to the browser during the login process.
This cookie will be present on the browser side and will be saved for a certain amount of time (depending on the lifetime specified when the cookie was created)
The next time you want to access this app, the browser will detect the cookie (if it still works), then the user will be automatically logged in, no need to enter a username or password, etc.
Spring Security provides two ways to implement Remember-me: a simple hash-based token (token) approach: Using a hash function to guarantee the security of cookie-based tokens. Persistent token mode: tokens generated by the use of databases or other persistent storage
This article shows the persistence token method (Persistent token approach)
and normal login different points:
1. In a persistent token mode, the database should contain a persistent_logins table, which can be created (or equivalent) using the following statement:
CREATE TABLE persistent_logins (
username varchar) NOT NULL,
series VARCHAR (+) not NULL,
token varchar ( ) not NULL,
last_used TIMESTAMP not NULL,
PRIMARY KEY (series)
);
This table contains username, last_used the timestamp of persistent login, security token implemented through spring Bcrypt. See here for more details.
2. Configure the Remember-me in spring security
Package com.websystique.springsecurity.configuration;
Import Javax.sql.DataSource;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.beans.factory.annotation.Qualifier;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import Org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
Import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
Import Org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
Import Org.springframework.security.core.userdetails.UserDetailsService;
Import Org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
Import Org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; @Configuration @EnableWebSecurity
public class Securityconfiguration extends Websecurityconfigureradapter {@Autowired @Qualifier ("Customuserdeta
Ilsservice ") Userdetailsservice Userdetailsservice;
@Autowired DataSource DataSource; @Autowired public void configureglobalsecurity (Authenticationmanagerbuilder auth) throws Exception {Auth.user
Detailsservice (Userdetailsservice);
} @Override protected void Configure (Httpsecurity http) throws Exception {http.authorizerequests () . Antmatchers ("/", "Home"). Permitall (). Antmatchers ("/admin/**"). Access ("Hasrole (' admin ')"). ANTMATC Hers ("/db/**"). Access ("Hasrole (' ADMIN ') and Hasrole (' DBA ')"). and (). Formlogin (). LoginPage ("/login"). Usern Ameparameter ("Ssoid"). Passwordparameter ("password"). and (). RememberMe (). Remembermeparameter ("Remember-me"). Tokenrepository (Persistenttokenrepository ()). Tokenvalidityseconds (86400). and (). CSRF (). and (). ExceptionhaNdling (). Accessdeniedpage ("/access_denied"); } @Bean Public Persistenttokenrepository persistenttokenrepository () {Jdbctokenrepositoryimpl token
Repositoryimpl = new Jdbctokenrepositoryimpl ();
Tokenrepositoryimpl.setdatasource (DataSource);
return Tokenrepositoryimpl; }
}
Notice how we call the RememberMe () method to configure Remember-me validation. By providing a check box with the HTPP parameter name Remember-me (which will be seen in the following screen).
We also indicated the tokenrepository (where the token is stored), and the token effective time (in seconds), the above code we provide is 1 days. In order to configure repository we injected the datasource.
This is how Remember-me (auto-Login) is implemented in Spring security.
You can also use Spring Security's built-in expressions to match the spring security tag, either for display or for hiding based on automatic login or full authentication.
The corresponding XML configuration form is configured above:
<beans:beans xmlns= "http://www.springframework.org/schema/security" xmlns:beans= "http// Www.springframework.org/schema/beans "xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation="
Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd Http://www.springframework.org/schema/security http://www.springframework.org/schema/security/ Spring-security-4.0.xsd ">
This is the process of implementing password encryption through spring Security's bcrypt.
The following is the complete code:
Use the following techniques or software spring 4.1.6.RELEASE spring Security 4.0.1.RELEASE Hibernate 4.3.6.Final MySQL Server 5.6 Maven 3 JDK 1.7 TOMCA T 8.0.21 Eclipse JUNO Service Release 2
Let's get started. 1th Step: The project file directory structure below is the final project directory structure
2nd Step: Update Pom.xml contains the required dependencies
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < Modelversion>4.0.0</modelversion> <groupId>com.websystique.springsecurity</groupId> <
Artifactid>springsecurityremembermeannotationexample</artifactid> <version>1.0.0</version> <packaging>war</packaging> <name>SpringSecurityRememberMeAnnotationExample</name> <PR Operties> <springframework.version>4.1.6.RELEASE</springframework.version> <springsecuri Ty.version>4.0.1.release</springsecurity.version>
Database Schema Section
---------------------------------------
3rd Step: Create a database schema and populate the simulation data
/* For REMEMBER-ME token storage Purpose */CREATE TABLE persistent_logins (username VARCHAR) not NULL, series
varchar (+) NOT NULL, token VARCHAR (+) NOT NULL, last_used TIMESTAMP NOT NULL, PRIMARY KEY (series)); /*all User ' s gets stored in App_user table*/CREATE TABLE App_user (ID BIGINT not NULL auto_increment, sso_id varch AR (+) NOT NULL, password varchar (+) NOT NULL, first_name varchar (+) NOT NULL, last_name varchar (+) NOT NULL
, email varchar (+) NOT NULL, state VARCHAR (+) NOT NULL, PRIMARY KEY (ID), UNIQUE (sso_id));
/* User_profile table contains all possible roles */CREATE TABLE User_profile (ID BIGINT not NULL auto_increment,
Type VARCHAR (+) not NULL, PRIMARY KEY (ID), UNIQUE (type)); /* JOIN table for Many-to-many relationship*/CREATE TABLE app_user_user_profile (user_id BIGINT not NULL, use r_profile_id BIGINT not NULL, PRIMARY KEY (user_id, user_profile_id), ConstraINT fk_app_user FOREIGN Key (user_id) REFERENCES App_user (ID), CONSTRAINT fk_user_profile FOREIGN KEY (user_profile_i
d) REFERENCES User_profile (id));
/* Populate user_profile Table */INSERT into user_profile (type) VALUES (' USER ');
INSERT into User_profile (type) VALUES (' ADMIN ');
INSERT into User_profile (type) VALUES (' DBA '); /* Populate one Admin User. We need only one user to demonstrate this example. You can add more as do in previous posts*/INSERT into App_user (sso_id, password, first_name, last_name, e-mail, state) V
Alues (' Sam ', ' abc125 ', ' Sam ', ' Smith ', ' samy@xyz.com ', ' Active '); /* Populate JOIN Table */INSERT into App_user_user_profile (user_id, user_profile_id) SELECT user.id, profile.id from a Pp_user user, User_profile profile where user.sso_id= ' Sam ' and profile.type= ' ADMIN ';
Security (Safety) Section-------------------------
4th step: Add the Spring Security configuration class
Package com.websystique.springsecurity.configuration;
Import Javax.sql.DataSource;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.beans.factory.annotation.Qualifier;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import Org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
Import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
Import Org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
Import Org.springframework.security.core.userdetails.UserDetailsService;
Import Org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
Import Org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; @Configuration @EnableWebSecurity
public class Securityconfiguration extends Websecurityconfigureradapter {@Autowired @Qualifier ("Customuserdeta
Ilsservice ") Userdetailsservice Userdetailsservice;
@Autowired DataSource DataSource; @Autowired public void configureglobalsecurity (Authenticationmanagerbuilder auth) throws Exception {Auth.user
Detailsservice (Userdetailsservice);
} @Override protected void Configure (Httpsecurity http) throws Exception {http.authorizerequests () . Antmatchers ("/", "Home"). Permitall (). Antmatchers ("/admin/**"). Access ("Hasrole (' admin ')"). ANTMATC Hers ("/db/**"). Access ("Hasrole (' ADMIN ') and Hasrole (' DBA ')"). and (). Formlogin (). LoginPage ("/login"). Usern Ameparameter ("Ssoid"). Passwordparameter ("password"). and (). RememberMe (). Remembermeparameter ("Remember-me"). Tokenrepository (Persistenttokenrepository ()). Tokenvalidityseconds (86400). and (). CSRF (). and (). ExceptionhaNdling (). Accessdeniedpage ("/access_denied"); } @Bean Public Persistenttokenrepository persistenttokenrepository () {Jdbctokenrepositoryimpl token
Repositoryimpl = new Jdbctokenrepositoryimpl ();
Tokenrepositoryimpl.setdatasource (DataSource);
return Tokenrepositoryimpl; }
}
5th step: Register SpringsecurityfilterThe following is the Springsecurityfilter (in the third step) of the Custom init War package registration class
Package com.websystique.springsecurity.configuration;
Import Org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class Securitywebapplicationinitializer extends Abstractsecuritywebapplicationinitializer {
}
The corresponding XML configuration: