什么是 Remember Me?
如果启用了 Remember Me
,登录后重启浏览器访问 http://localhost:8080/admin 就不需要重新登录了。
Spring Security 5 已经默认启动了 Remember Me 功能,Spring Security 4 需要按照下面进行配置。给 Spring Security 添加 Remember Me 功能,只需要 2 步:
Login.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <html> <head> <title>Login Page</title> </head> <body> <span th:text="${error}" th:if="${error} != null"></span> <span th:text="${logout}" th:if="${logout} != null"></span>
<form name="loginForm" action="/login" method="POST"> Username: <input type="text" name="username"/><br> Password: <input type="password" name="password"/><br> <input type="checkbox" name="remember-me"/> Remember Me<br> <input name="submit" type="submit" value="登陆"/> </form> </body> </html>
|
spring-security.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| <?xml version="1.0" encoding="UTF-8"?> <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.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true"> <intercept-url pattern="/admin" access="hasRole('ADMIN')"/> <intercept-url pattern="/login" access="permitAll"/>
<form-login login-page="/login" login-processing-url="/login" default-target-url ="/hello" authentication-failure-url="/login?error=1" username-parameter="username" password-parameter="password"/> <access-denied-handler error-page="/deny"/> <logout logout-url="/logout" logout-success-url="/login?logout=1"/>
<csrf disabled="true"/> <remember-me key="uniqueAndSecret" token-validity-seconds="2592000"/> </http>
<beans:bean id="userDetailsService" class="com.xtuer.service.MyUserDetailsService"/> <authentication-manager> <authentication-provider user-service-ref="userDetailsService"> <password-encoder hash="bcrypt"/> </authentication-provider> </authentication-manager> </beans:beans>
|
测试