这里接着上篇的自定义过滤器,这里主要的是配置自定义认证处理的过滤器,并加入到FilterChain的过程。

在我们自己不在xml做特殊的配置情况下,security默认的做认证处理的过滤器为UsernamePasswordAuthenticationFilter,通过查看源码知道,做认证处理的方法为attemptAuthentication,这个方法的主要作用就是将用户输入的账号和密码,封装成一个UsernamePasswordAuthenticationToken对象,然后通过setDetails方法将这个对象储存起来,然后调用this.getAuthenticationManager().authenticate(authRequest)方法返回一个Authentication对象。其中这个过程this.getAuthenticationManager().authenticate(authRequest)又调用的其他的许多类,这里简单的讲解下:

UsernamePasswordAuthenticationFilter-->ProviderManager-->AbstractUserDetailsAuthenticationProvider-->DaoAuthenticationProvider-->JdbcDaoImpl

根据这个顺序我画了个图方便记忆

当输入用户名和密码后,点击登陆到达UsernamePasswordAuthenticationFilter的attemptAuthentication方法,这个方法是登陆的入口,然后其调用ProviderManager中的authenticate方法,而ProviderManager委托给AbstractUserDetailsAuthenticationProvider的authenticate做,然后AbstractUserDetailsAuthenticationProvider又调用DaoAuthenticationProvider中的retrieveUser,在DaoAuthenticationProvider类的retrieveUser方法中,因为要通过输入的用户名获取到一个UserDetails,所以其调用JdbcDaoImpl中的loadUserByUsername方法,该方法给它的调用者返回一个查询到的用户(UserDetails),最终AbstractUserDetailsAuthenticationProvider的authenticate方法中会得到一个UserDetails对象user,然后接着执行preAuthenticationChecks.check(user)和additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);其中前面这个方法是判断,查询的用户是否可用或被锁等,后面的则是判断查询到的user对象的密码是否和authentication(这个对象其实就是存储用户输入的用户名和密码)的密码一样,若一样则表示登陆成功,若错误,则throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), userDetails);Bad credentials这个消息就是登陆失败后的信息。初步的讲解了登陆过程中类的调用,那么下面这个例子就是自定义一个MyUsernamePasswordAuthenticationFilter来代替默认的  UsernamePasswordAuthenticationFilter。

一、自定义MyUsernamePasswordAuthenticationFilter

这个类可以继承UsernamePasswordAuthenticationFilter,然后重写attemptAuthentication方法,这个方法是登陆的入口方法。
  1. package com.zmc.demo;
  2.  
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. import javax.servlet.http.HttpSession;
  6.  
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.security.authentication.AuthenticationManager;
  9. import org.springframework.security.authentication.AuthenticationServiceException;
  10. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  11. import org.springframework.security.core.Authentication;
  12. import org.springframework.security.core.AuthenticationException;
  13. import org.springframework.security.core.context.SecurityContextHolder;
  14. import org.springframework.security.core.userdetails.UserDetailsService;
  15. import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
  16. import org.springframework.security.crypto.password.PasswordEncoder;
  17. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  18. import org.springframework.util.StringUtils;
  19.  
  20. /**
  21. * @classname MyUsernamePasswordAuthenticationFilter
  22. * @author ZMC
  23. * @time 2017-1-13
  24. *
  25. */
  26. public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
  27.  
  28. public static final String USERNAME = "j_username";
  29. public static final String PASSWORD = "j_password";
  30. /**
  31. * @Description:用户登录验证方法入口
  32. * @param :args
  33. * @return
  34. * @throws Exception
  35. */
  36. @Override
  37. public Authentication attemptAuthentication(HttpServletRequest request,
  38. HttpServletResponse response) throws AuthenticationException {
  39.  
  40. if (!request.getMethod().equals("POST")) {
  41. throw new AuthenticationServiceException(
  42. "Authentication method not supported: "
  43. + request.getMethod());
  44. }
  45. String username = this.obtainUsername(request);
  46. String password = this.obtainPassword(request);
  47. // 加密密码(根据“密码{用户名})进行加密
  48. // String sh1Password = password + "{" + username + "}";
  49. // PasswordEncoder passwordEncoder = new
  50. // StandardPasswordEncoderForSha1();
  51. // String result = passwordEncoder.encode(sh1Password);
  52. // UserInfo userDetails = (UserInfo)
  53. // userDetailsService.loadUserByUsername(username);
  54. if (username == null) {
  55. username = "";
  56. }
  57.  
  58. if (password == null) {
  59. password = "";
  60. }
  61.  
  62. username = username.trim();
  63.  
  64. UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
  65. username, password);
  66.  
  67. // Allow subclasses to set the "details" property
  68. setDetails(request, authRequest);
  69.  
  70. return this.getAuthenticationManager().authenticate(authRequest);
  71.  
  72. }
  73.  
  74. /**
  75. * @Description:获取密码
  76. * @param :args
  77. * @return
  78. * @throws Exception
  79. */
  80. @Override
  81. protected String obtainPassword(HttpServletRequest request) {
  82. // TODO Auto-generated method stub
  83. Object obj = request.getParameter(PASSWORD);
  84. return null == obj ? "" : obj.toString();
  85. }
  86.  
  87. /**
  88. * @Description:获取用户名
  89. * @param :args
  90. * @return
  91. * @throws Exception
  92. */
  93. @Override
  94. protected String obtainUsername(HttpServletRequest request) {
  95. // TODO Auto-generated method stub
  96. Object obj = request.getParameter(USERNAME);
  97. return null == obj ? "" : obj.toString().trim().toLowerCase();
  98. }
  99.  
  100. }

上述的代码这样写其实和默认的UsernamePasswordAuthenticationFilter并没有什么区别,但是这里主要是学会将自定义的Filter加入到security中的FilterChain中去,实际上这个方法中,一般会直接验证用户输入的和通过用户名从数据库里面查到的用户的密码是否一致,如果不一致,就抛异常,否则继续向下执行。

二、配置MyUsernamePasswordAuthenticationFilter并将其加入到FilterChain中去

MyUsernamePasswordAuthenticationFilter有filterProcessesUrl属性为登陆的过滤的地址,authenticationManager为authentication-manager标签中配置的东西,authenticationSuccessHandler为验证成功后跳转的处理器,authenticationFailureHandler为验证失败的处理器。另外还要配置一个出登陆引导的处bean:LoginUrlAuthenticationEntryPoint
配置代码如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans:beans xmlns="http://www.springframework.org/schema/security"
  3. xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  6. http://www.springframework.org/schema/context
  7. http://www.springframework.org/schema/context/spring-context-3.1.xsd
  8. http://www.springframework.org/schema/tx
  9. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  10. http://www.springframework.org/schema/security
  11. http://www.springframework.org/schema/security/spring-security.xsd">
  12.  
  13. <http pattern="/login.jsp" security="none"></http>
  14. <http auto-config="false" entry-point-ref="loginUrlAuthenticationEntryPoint">
  15. <!-- <form-login login-page="/login.jsp" default-target-url="/index.jsp"
  16. authentication-failure-url="/login.jsp?error=true" /> -->
  17. <logout invalidate-session="true" logout-success-url="/login.jsp"
  18. logout-url="/j_spring_security_logout" />
  19. <custom-filter ref="myUsernamePasswordAuthenticationFilter" position="FORM_LOGIN_FILTER" />
  20. <!-- 通过配置custom-filter来增加过滤器,before="FILTER_SECURITY_INTERCEPTOR"表示在SpringSecurity默认的过滤器之前执行。 -->
  21. <custom-filter ref="filterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR" />
  22. </http>
  23. <beans:bean id="loginUrlAuthenticationEntryPoint"
  24. class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
  25. <beans:property name="loginFormUrl" value="/login.jsp" />
  26. </beans:bean>
  27.  
  28. <!-- 数据源 -->
  29. <beans:bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
  30. destroy-method="close">
  31. <!-- 此为c3p0在spring中直接配置datasource c3p0是一个开源的JDBC连接池 -->
  32. <beans:property name="driverClass" value="com.mysql.jdbc.Driver" />
  33. <beans:property name="jdbcUrl"
  34. value="jdbc:mysql://localhost:3306/springsecuritydemo?useUnicode=true&characterEncoding=UTF-8" />
  35. <beans:property name="user" value="root" />
  36. <beans:property name="password" value="" />
  37. <beans:property name="maxPoolSize" value="50"></beans:property>
  38. <beans:property name="minPoolSize" value="10"></beans:property>
  39. <beans:property name="initialPoolSize" value="10"></beans:property>
  40. <beans:property name="maxIdleTime" value="25000"></beans:property>
  41. <beans:property name="acquireIncrement" value="1"></beans:property>
  42. <beans:property name="acquireRetryAttempts" value="30"></beans:property>
  43. <beans:property name="acquireRetryDelay" value="1000"></beans:property>
  44. <beans:property name="testConnectionOnCheckin" value="true"></beans:property>
  45. <beans:property name="idleConnectionTestPeriod" value="18000"></beans:property>
  46. <beans:property name="checkoutTimeout" value="5000"></beans:property>
  47. <beans:property name="automaticTestTable" value="t_c3p0"></beans:property>
  48. </beans:bean>
  49.  
  50. <beans:bean id="builder" class="com.zmc.demo.JdbcRequestMapBulider">
  51. <beans:property name="dataSource" ref="dataSource" />
  52. <beans:property name="resourceQuery"
  53. value="select re.res_string,r.name from role r,resc re,resc_role rr where
  54. r.id=rr.role_id and re.id=rr.resc_id" />
  55. </beans:bean>
  56.  
  57. <beans:bean id="myUsernamePasswordAuthenticationFilter"
  58. class="com.zmc.demo.MyUsernamePasswordAuthenticationFilter
  59. ">
  60. <beans:property name="filterProcessesUrl" value="/j_spring_security_check" />
  61. <beans:property name="authenticationManager" ref="authenticationManager" />
  62. <beans:property name="authenticationSuccessHandler"
  63. ref="loginLogAuthenticationSuccessHandler" />
  64. <beans:property name="authenticationFailureHandler"
  65. ref="simpleUrlAuthenticationFailureHandler" />
  66. </beans:bean>
  67.  
  68. <beans:bean id="loginLogAuthenticationSuccessHandler"
  69. class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
  70. <beans:property name="targetUrlParameter" value="/index.jsp" />
  71. </beans:bean>
  72.  
  73. <beans:bean id="simpleUrlAuthenticationFailureHandler"
  74. class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
  75. <beans:property name="defaultFailureUrl" value="/login.jsp" />
  76. </beans:bean>
  77.  
  78. <!-- 认证过滤器 -->
  79. <beans:bean id="filterSecurityInterceptor"
  80. class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
  81. <!-- 用户拥有的权限 -->
  82. <beans:property name="accessDecisionManager" ref="accessDecisionManager" />
  83. <!-- 用户是否拥有所请求资源的权限 -->
  84. <beans:property name="authenticationManager" ref="authenticationManager" />
  85. <!-- 资源与权限对应关系 -->
  86. <beans:property name="securityMetadataSource" ref="securityMetadataSource" />
  87. </beans:bean>
  88.  
  89. <!-- acl领域模型 -->
  90. <beans:bean class="com.zmc.demo.MyAccessDecisionManager" id="accessDecisionManager">
  91. </beans:bean>
  92. <!-- -->
  93. <authentication-manager alias="authenticationManager">
  94. <authentication-provider>
  95. <jdbc-user-service data-source-ref="dataSource"
  96. users-by-username-query="select username,password,status as enabled from user where username = ?"
  97. authorities-by-username-query="select user.username,role.name from user,role,user_role
  98. where user.id=user_role.user_id and
  99. user_role.role_id=role.id and user.username=?" />
  100. </authentication-provider>
  101. </authentication-manager>
  102.  
  103. <beans:bean id="securityMetadataSource"
  104. class="com.zmc.demo.MyFilterInvocationSecurityMetadataSource">
  105. <beans:property name="builder" ref="builder"></beans:property>
  106. </beans:bean>
  107.  
  108. </beans:beans>

三、结果

因为处理验证的过滤器不一样,其他的和教程五一样,结果这里就不展示了,参考前面的教程。

Spring Security教程(六):自定义过滤器进行认证处理的更多相关文章

  1. Spring Security教程(五):自定义过滤器从数据库从获取资源信息

    在之前的几篇security教程中,资源和所对应的权限都是在xml中进行配置的,也就在http标签中配置intercept-url,试想要是配置的对象不多,那还好,但是平常实际开发中都往往是非常多的资 ...

  2. Spring Security教程(八):用户认证流程源码详解

    本篇文章主要围绕下面几个问题来深入源码: 用户认证流程 认证结果如何在多个请求之间共享 获取认证用户信息 一.用户认证流程 上节中提到Spring Security核心就是一系列的过滤器链,当一个请求 ...

  3. Spring Security教程(三):自定义表结构

    在上一篇博客中讲解了用Spring Security自带的默认数据库存储用户和权限的数据,但是Spring Security默认提供的表结构太过简单了,其实就算默认提供的表结构很复杂,也不一定能满足项 ...

  4. Spring Security教程(二):自定义数据库查询

    Spring Security教程(二):自定义数据库查询   Spring Security自带的默认数据库存储用户和权限的数据,但是Spring Security默认提供的表结构太过简单了,其实就 ...

  5. Spring Security 解析(六) —— 基于JWT的单点登陆(SSO)开发及原理解析

    Spring Security 解析(六) -- 基于JWT的单点登陆(SSO)开发及原理解析   在学习Spring Cloud 时,遇到了授权服务oauth 相关内容时,总是一知半解,因此决定先把 ...

  6. Spring Security 教程 大牛的教程

    https://www.iteye.com/blog/elim-2247073 Spring Security 教程 Spring Security(20)——整合Cas Spring Securit ...

  7. Spring Security教程(三)

    在上一篇博客中讲解了用Spring Security自带的默认数据库存储用户和权限的数据,但是Spring Security默认提供的表结构太过简单了,其实就算默认提供的表结构很复杂,也不一定能满足项 ...

  8. Spring Security 实战干货:图解Spring Security中的Servlet过滤器体系

    1. 前言 我在Spring Security 实战干货:内置 Filter 全解析对Spring Security的内置过滤器进行了罗列,但是Spring Security真正的过滤器体系才是我们了 ...

  9. Spring 系列教程之自定义标签的解析

    Spring 系列教程之自定义标签的解析 在之前的章节中,我们提到了在 Spring 中存在默认标签与自定义标签两种,而在上一章节中我们分析了 Spring 中对默认标签的解析过程,相信大家一定已经有 ...

随机推荐

  1. VB数组的清除

    在一个程序中,同一数组只能用Dim语句定义一次.但有时可能需要清除数组的内容或对数组重新定义,这可以用:Erase语句来实现. 格式:Erase(数组名)[,(数组名)] 功能:用于重新初始化静态数组 ...

  2. 关于gitblit成功启动,但在阿里云外网地址无法访问的问题

    1.配置/data/defaults.properties server.httpBindInterface= 此处什么都不要填空着就好. # Specify the interface for Je ...

  3. __set() __get() _isset() __unset() 在__unset() 在类中没有事先声明和已经声明过的属性调用unset的区别

    <?php //echo strtr("I Love Mysql, Love PHP", "Mysql","MYSQL"); //$a ...

  4. Jenkins的安装(最为简单的安装方法)

    1.Jenkins的安装(最为简单的安装方法) (1)下载Jenkins(一个war文件) (2)cmd运行:java -jar jenkins.war [Jenkins需要IDK1.5以上的版本] ...

  5. 下载完整版Chrome离线安装文件的官方地址

    只在自己账号下安装Download Google Chrome Standalone Offline Installer (32-bit)  http://www.google.com/chrome/ ...

  6. 给Java程序员的几条建议

    对于Java程序猿学习的建议 这一部分其实也算是今天的重点,这一部分用来回答很多群里的朋友所问过的问题,那就是LZ你是如何学习Java的,能不能给点建议? 今天LZ是打算来点干货,因此咱们就不说一些学 ...

  7. 【转】【MySQL】MySQL的双机互信实战

    [转]https://www.cnblogs.com/mchina/archive/2013/03/15/2956017.html MySQL双机实战原理:利用ssh传输文件,通过公.私钥的共享,实现 ...

  8. 远程阿里云window服务器报错身份验证错误

    整理文章,很久之前遇到的一个问题,一直呆在草稿箱,特发布出来,帮助可能遇到该问题的人 mstsc连接时报错如下 解决方法: 修改本地安全组策略[安全组  gpedit.msc]

  9. 简述MVC

    强调:mvc不是框架而是一种设计模式 分层结构的好处:1.降低了代码之间的耦合性 2.提高了代码的重用性 一. 概述 MVC的全名Model View Controller,即模型-视图-控制器的缩写 ...

  10. Debug 路漫漫-01

    运行到子函数时提示报错:  === 这个断点一步步debug下来是顺利的,但是咋就超出数组范围了呢,这会是什么问题. ——sess肯定超过索引了,那个sess(:,2)的值肯定超过V的行数了. ——由 ...