请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

spring security 的logout功能

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吗?

正在回答 回答被采纳积分+3

1回答

Jimin 2018-01-14 15:56:11

你好,我看你这些配置写的很详细了,没看出有什么问题。spring security的logout有提供好的的请求,j_spring_security_logout,你可以试试看,也可以通过做些配置改成自己希望的url,你可以试试。祝你学习愉快~

0 回复 有任何疑惑可以回复我~
  • 提问者 慕仙4974986 #1
    报错呀老师cookie没有清除呀
    
    回复 有任何疑惑可以回复我~ 2018-01-14 15:58:59
  • Jimin 回复 提问者 慕仙4974986 #2
    你的错我猜测是直接访问 j_spring_security_logout 这个接口导致的,目前你贴出来的代码里我看到你指定了logout url,然后自己实现的logout功能。我刚才的回答是期望你去掉自定义的logout url,然后再访问spring security这个框架默认提供的logout接口j_spring_security_logout, 默认的接口里会去做相应的cookie的清理,你再试试看。如果还有错,记得把修改的代码和错误发出来,方便我定位问题~
    回复 有任何疑惑可以回复我~ 2018-01-14 16:20:22
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信