Spring Security教程(10)---- 自定义登录成功后的处理程序及修改默认验证地址

form-login配置中的authentication-success-handler-ref可以让手动注入登录成功后的处理程序,需要实现AuthenticationSuccessHandler接口。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <sec:form-login login-page="/login.jsp"  
  2.     login-processing-url="/login.do"  
  3.     authentication-failure-url="/login.jsp"  
  4.     authentication-success-handler-ref="authenticationSuccessHandler"  
  5. />  
springSecurity默认的登录用户验证路径为:j_spring_security_check,这个路径是可以通过l ogin-processing-url 来自己定义,比如我的就定义成了login.do。

然后在前台登录页面中改下form中的action就可以了。

配置文件,注意这里的defaultTargetUrl,本来这个是在form-login中,配置的但是如果我们自己定义登录成功后的处理程序后它就不起作用了,所以这个跳转也需要我们在自定义程序中处理。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <bean id="authenticationSuccessHandler" class="com.zrhis.system.security.SimpleLoginSuccessHandler">  
  2.     <property name="defaultTargetUrl" value="/WEB-INF/app.jsp"></property>  
  3.     <property name="forwardToDestination" value="true"></property>  
  4. </bean>  
SimpleLoginSuccessHandler,这个类主要处理登录后的处理,我处理的是登录后记录用户的IP地址和登录时间,代码如下 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.zrhis.system.security;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.Date;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. import org.apache.commons.logging.Log;  
  11. import org.apache.commons.logging.LogFactory;  
  12. import org.springframework.beans.factory.InitializingBean;  
  13. import org.springframework.beans.factory.annotation.Autowired;  
  14. import org.springframework.dao.DataAccessException;  
  15. import org.springframework.security.core.Authentication;  
  16. import org.springframework.security.web.DefaultRedirectStrategy;  
  17. import org.springframework.security.web.RedirectStrategy;  
  18. import org.springframework.security.web.authentication.AuthenticationSuccessHandler;  
  19. import org.springframework.transaction.annotation.Propagation;  
  20. import org.springframework.transaction.annotation.Transactional;  
  21. import org.springframework.util.StringUtils;  
  22.   
  23. import com.zrhis.base.exception.InitializationException;  
  24. import com.zrhis.system.bean.SysUsers;  
  25. import com.zrhis.system.repository.SysUsersRepository;  
  26.   
  27. public class SimpleLoginSuccessHandler implements AuthenticationSuccessHandler,InitializingBean {  
  28.       
  29.     protected Log logger = LogFactory.getLog(getClass());  
  30.       
  31.     private String defaultTargetUrl;  
  32.       
  33.     private boolean forwardToDestination = false;  
  34.       
  35.     private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();  
  36.       
  37.     @Autowired  
  38.     private SysUsersRepository sysUsersRepository;  
  39.       
  40.     /* (non-Javadoc) 
  41.      * @see org.springframework.security.web.authentication.AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication) 
  42.      */  
  43.     @Override  
  44.     @Transactional(readOnly=false,propagation= Propagation.REQUIRED,rollbackFor={Exception.class})  
  45.     public void onAuthenticationSuccess(HttpServletRequest request,  
  46.             HttpServletResponse response, Authentication authentication)  
  47.             throws IOException, ServletException {  
  48.           
  49.         this.saveLoginInfo(request, authentication);  
  50.           
  51.         if(this.forwardToDestination){  
  52.             logger.info("Login success,Forwarding to "+this.defaultTargetUrl);  
  53.               
  54.             request.getRequestDispatcher(this.defaultTargetUrl).forward(request, response);  
  55.         }else{  
  56.             logger.info("Login success,Redirecting to "+this.defaultTargetUrl);  
  57.               
  58.             this.redirectStrategy.sendRedirect(request, response, this.defaultTargetUrl);  
  59.         }  
  60.     }  
  61.       
  62.     @Transactional(readOnly=false,propagation= Propagation.REQUIRED,rollbackFor={Exception.class})  
  63.     public void saveLoginInfo(HttpServletRequest request,Authentication authentication){  
  64.         SysUsers user = (SysUsers)authentication.getPrincipal();  
  65.         try {  
  66.             String ip = this.getIpAddress(request);  
  67.             Date date = new Date();  
  68.             user.setLastLogin(date);  
  69.             user.setLoginIp(ip);  
  70.             this.sysUsersRepository.saveAndFlush(user);  
  71.         } catch (DataAccessException e) {  
  72.             if(logger.isWarnEnabled()){  
  73.                 logger.info("无法更新用户登录信息至数据库");  
  74.             }  
  75.         }  
  76.     }  
  77.       
  78.     public String getIpAddress(HttpServletRequest request){    
  79.         String ip = request.getHeader("x-forwarded-for");    
  80.         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
  81.             ip = request.getHeader("Proxy-Client-IP");    
  82.         }    
  83.         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
  84.             ip = request.getHeader("WL-Proxy-Client-IP");    
  85.         }    
  86.         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
  87.             ip = request.getHeader("HTTP_CLIENT_IP");    
  88.         }    
  89.         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
  90.             ip = request.getHeader("HTTP_X_FORWARDED_FOR");    
  91.         }    
  92.         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
  93.             ip = request.getRemoteAddr();    
  94.         }    
  95.         return ip;    
  96.     }  
  97.   
  98.     public void setDefaultTargetUrl(String defaultTargetUrl) {  
  99.         this.defaultTargetUrl = defaultTargetUrl;  
  100.     }  
  101.   
  102.     public void setForwardToDestination(boolean forwardToDestination) {  
  103.         this.forwardToDestination = forwardToDestination;  
  104.     }  
  105.   
  106.     /* (non-Javadoc) 
  107.      * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() 
  108.      */  
  109.     @Override  
  110.     public void afterPropertiesSet() throws Exception {  
  111.         if(StringUtils.isEmpty(defaultTargetUrl))  
  112.             throw new InitializationException("You must configure defaultTargetUrl");  
  113.           
  114.     }    
  115.       
  116. }  
其中getIpAddress方法摘自网络,如有雷同纯属必然。

实现InitializingBean,在afterPropertiesSet中我们验证defaultTargetUrl是否为空,如果为空就抛出异常,因为这个地址是必须的。可以根据自己的情况来选择要不要加验证。

如果实现InitializingBean在程序启动是Spring在创建完这个类并注入属性后会自动执行afterPropertiesSet,所以我们的一些初始化的操作也是可以在这里完成的。

onAuthenticationSuccess是主要的接口这个是登录成功后Spring调用的方法,而我们的跳转和保存用户信息都是在这里完成的。

RedirectStrategy是Spring提供的一个客户端跳转的工具类。使用它可以支持“/index.jsp”这种地址,同时可以保证服务器跳转和客户端跳转的路径一致。

加入我们的项目名为my ,项目访问地址为http://localhost:8080/my

现在要使用客户端跳转到 "/login.jsp" 如果是response.sendRedirect 会直接跳转到http://localhost:8080/login.jsp

而使用redirectStrategy.sendRedirect则会跳转到http://localhost:8080/my/login.jsp

在redirectStrategy中,'/'代表的是项目根目录而不是服务器根目录。


  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值