spring-security(五)java config-sample之rememberme

Foreword:
  This article briefly introduces how to use the remember me function provided by spring-security. The parameter name and configuration method adopts the default configuration of spring. The method of customization will be explained in detail in the subsequent chapters for further discussion.
Environment:
  spring boot Version: 1.5.4.RELEASE

1. The project structure



application.yml file is placed in the src/main/resources/ directory

2. The configuration class SecurityConfig.java
/**
 *
 */
package nariis.chengf.security.samples.javaconfig.remeberme;

import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 * @author: Author: chengaofeng
 * @date: Creation time: 2018-01-16 19:32:47
 * @Description: EVERYTHING
 * @version V1.0
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	public void auth(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication().withUser("user").password("password").authorities("ROLE_USER");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
		.csrf()
			.disable()
		.authorizeRequests()
			.anyRequest().authenticated()
			.and()
		.formLogin()
			.loginPage("/login.html")
			.permitAll()
			.and()
		.rememberMe()
			.and()
		.logout()
			.logoutSuccessUrl("/login.html");
	}
}


For simplicity, the csrf check is disabled in this example, using memory-based authentication
2. Start the class RemeberMeApp.java
package nariis.chengf.security.samples.javaconfig.remeberme;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Hello world!
 *
 */
@SpringBootApplication
public class RemeberMeApp
{
    public static void main( String[] args )
    {
        SpringApplication.run(RemeberMeApp.class, args);
    }
}

3. The project's pom.xml
<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>nariis.chengf</groupId>
	<artifactId>security-samples-javaconfig-remeberme</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>security-samples-javaconfig-remeberme</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencyManagement>

		<dependencies>
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-starter-parent</artifactId>
				<version>1.5.4.RELEASE</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<executions>
					<execution>
						<goals>
							<goal>repackage</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<mainClass>${start-class}</mainClass>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

4. Login page login.html
<html xmlns:th="http://www.thymeleaf.org">
	<head th:include="layout :: head(title=~{::title},links=~{})">
		<title>Please Login</title>
	</head>
	<body th:include="layout :: body" th:with="content=~{::content}">
		<div th:fragment="content">
			<form name="f" th:action="@{/login}" method="post">
				<fieldset>
					<legend>Please Login</legend>
					<div th:if="${param.error}" class="alert alert-error">Invalid
						username and password.</div>
					<div th:if="${param.logout}" class="alert alert-success">You
						have been logged out.</div>
					<label for="username">Username</label> <input type="text"
						id="username" name="username" /> <label for="password">Password</label>
					<input type="password" id="password" name="password" /> <label
						for="remember-me">Remember Me?</label> <input type="checkbox"
						id="remember-me" name="remember-me" />
					<div class="form-actions">
						<button type="submit" class="btn">Log in</button>
					</div>
				</fieldset>
			</form>
		</div>
	</body>
</html>

A checkbox named remember-me is set up, because the default configuration of spring is used, the name here must be called this

5. The default welcome page index.html after successful login
<!DOCTYPE html>
<html>
<head>
<title>Static</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
	hello! wait for 2 minutes and refresh the browser,you will still be here.
</body>
</html>

6. Project configuration file application.yml
server:
  session:
    timeout: 120

Because the default survival time of the session with embedded tomcat in spring is 30 minutes, in order to better verify the remember me function, we changed the survival time of the session to 2 minutes
. 7. Start the project
  and select the startup class, select Run As -> Java application, after the normal startup, enter http://localhost:8080/login.html in the browser.
Under normal circumstances, it will enter the following interface.



Enter user name: user, password: password, select Remember me, click login, and then we We will be redirected to the welcome page.



After that, let us wait for more than two minutes for the session to expire, refresh the interface, and we will find that we are still in the login state. If we did not select remember me in the previous login interface, we will wait for more than two minutes on this page. After the refresh, we will be redirected to the login page, requiring us to log in again.

By default , spring uses TokenBasedRememberMeServices by default. In the onLoginSuccess method of this class, it can be clearly seen that the default remember time is TWO_WEEKS_S (two weeks)

Download the source code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326156373&siteId=291194637