spring security remember me实现以后
----------------------
@Controller
public class DemoController {
@Autowired
@Qualifier("tokenRepositoryDAO")
private PersistentTokenRepository tokenRepository;
@RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
public String homePage(ModelMap model) {
model.addAttribute("greeting", "Hi, 欢迎光临. ");
return "welcome";
}
@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(ModelMap model) {
model.addAttribute("user", getPrincipal());
return "admin";
}
@RequestMapping(value = "/db", method = RequestMethod.GET)
public String dbaPage(ModelMap model) {
model.addAttribute("user", getPrincipal());
return "dba";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(ModelMap model) {
return "login";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logoutPage(HttpServletRequest request,
HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (auth != null) {
//tokenRepository.removeUserTokens(getPrincipal());
new CookieClearingLogoutHandler("remember-me").logout(request, response, auth);
//new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "welcome";
}
@RequestMapping(value = "/accessDenied", method = RequestMethod.GET)
public String accessDeniedPage(ModelMap model) {
model.addAttribute("user", getPrincipal());
return "accessDenied";
}
private String getPrincipal() {
String userName = null;
// 当前的验证对象
Authentication authen = SecurityContextHolder.getContext().getAuthentication();
// 用户对象
Object principal = authen.getPrincipal();
if (principal instanceof UserDetails) {
// 用户名
userName = ((UserDetails) principal).getUsername();
} else {
userName = principal.toString();
}
return userName;
}
}
登出时,cookie信息已经清除,但是关闭浏览器后还能记住原来的账户名,和密码。这是怎么回事?
---------------
package cn.com.security.demo.config;
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.authentication.dao.DaoAuthenticationProvider;
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.builders.WebSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
private static final String KEY = "waylau.com";
@Autowired
@Qualifier("customSuccessHandler")
private AuthenticationSuccessHandler successHandler;
@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;
@Autowired
@Qualifier("tokenRepositoryDAO")
private PersistentTokenRepository tokenRepository;
/*@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(userDetailsService);
auth.inMemoryAuthentication().withUser("user_user").password("123456").roles("USER");// ROLE_USER
auth.inMemoryAuthentication().withUser("user_admin").password("123456").roles("ADMIN");
auth.inMemoryAuthentication().withUser("user_dba_admin").password("123456").roles("ADMIN", "DBA");// dba have two roles.
}
*/
//初始化权限管理(1.有那些用户 2.有那些角色 3.用户权限分配)
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.inMemoryAuthentication().withUser("user_user").password("123456").roles("USER");
// auth.inMemoryAuthentication().withUser("user_admin").password("123456").roles("ADMIN");
// auth.inMemoryAuthentication().withUser("user_dba_admin").password("123456").roles("ADMIN","DBA");
//auth.userDetailsService(userDetailsService);//实现非加密密码验证
auth.authenticationProvider(createDaoAuthenticationProvider()); //加密密码验证
//如果两个都设置了,两个都执行,只要有一个验证通过,就直接通过。
}
@Bean(name="passwordEncoder")
public PasswordEncoder getPasswordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean(name="daoAuthenticationProvider")
public DaoAuthenticationProvider createDaoAuthenticationProvider(){
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);//记住我,一定要设置
provider.setPasswordEncoder(getPasswordEncoder());
return provider;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/","/home","/test/**").permitAll()//所有人都可以访问
.antMatchers("/admin/**").access("hasRole('ADMIN')")//制定ADMIN角色能访问的资源
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")//具备ADMIN和DBA角色可以访问
.and()
//.formLogin()//使用系统的登录界面
.formLogin()
.loginPage("/login")
.permitAll()
.successHandler(successHandler)
.usernameParameter("userName")
.passwordParameter("password")
.and().logout().logoutUrl("/logout").deleteCookies("remember-me")
.and()
.rememberMe().key(KEY).rememberMeParameter("remember-me")//页面参数名称
.tokenRepository(tokenRepository)
.tokenValiditySeconds(3000) //有效时间 秒
.and()
.csrf() //支持夸站伪造的处理
.and().exceptionHandling().accessDeniedPage("/accessDenied");//没有权限返回的请求URL
}
@Override
public void configure(WebSecurity web) throws Exception {
//忽略web的静态资源不做拦截。
web.ignoring().antMatchers("/js/**","/css/**","/images/**");
}
}
-----login.jsp----------
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login page</title>
</head>
<body>
<form action="login" method="post">
UserName:<input type='text' name='userName'><br/>
Password:<input type='password' name='password'><br/>
<input type="checkbox" id="rememberme" name="remember-me"> Remember Me
<!-- 隐藏的动态标记 实现防备 跨站伪造 csrf -->
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<input type='submit' value='登录'/>
</form>
<c:if test="${param.error != null }">
<script type="text/javascript">
alert('用户名或密码错误');
</script>
</c:if>
</body>
</html>
-------------
spring security实现remember me后的退出功能怎么实现,我的 SecurityConfiguration配置的对吗?
老师有事例么?有demo吗?