Spring Security 3.1 自定义 authentication provider

前言

在使用Spring Security的时候,遇到一个比较特殊的情况,需要根据用户名、邮箱等多个条件去验证用户或者使用第三方的验证服务来进行用户名和密码的判断,这样SS(Spring Security,一下简称SS)内置的authentication provider和user detail service就不能用了,花了一些时间去寻找其他的办法。

前置条件

  • Spring MVC 结构的Web项目
  • Spring Security
  • 使用第三方的Service验证用户名密码(并非数据库或者OpenID等SS已经支持的服务)

需求

  • 根据用户输入的用户名和密码验证登录

问题分析

在尝试了修改Filter、替换SS内置的Filter之后,发现了一个比较简单的方法,这里简单的讲讲思路。

先看看SS验证用户名和密码的过程 :

DelegatingFilterProxy(Security filter chain):

  1.   ConcurrentSessionFilter
  2.   SecurityContextPersistenceFilter
  3.   LogoutFilter
  4.   UsernamePasswordAuthenticationFilter
  5.   RequestCacheAwareFilter
  6.   SecurityContextHolderAwareRequestFilter
  7.   RememberMeAuthenticationFilter
  8.   AnonymousAuthenticationFilter
  9.   SessionManagementFilter
  10.   ExceptionTranslationFilter
  11.   FilterSecurityInterceptor

这些都是内置的Filter,请求会从上往下依次过滤。这里由于我们主要关心用户名和密码的验证,所以就要从UsernamePasswordAuthenticationFilter 下手了。(UsernamePasswordAuthenticationFilter需要AuthenticationManager去进行验证。)

在SS的配置文件里面可以看到,如何给SS传递用户验证信息数据源(设置AuthenticationManager):

	<authentication-manager>
		<authentication-provider>
			<user-service>
				<user name="admin" authorities="ROLE_USER" password="admin" />
			</user-service>
		</authentication-provider>
	</authentication-manager>

当然这里是一个最简单的配置,跟踪一下代码就会发现:

  • 内置的AuthenticationManager为org.springframework.security.authentication.ProviderManager
  • 默认的AuthenticationProvider为org.springframework.security.authentication.dao.DaoAuthenticationProvider
  • 再往下看,这个authentication provider使用org.springframework.security.core.userdetails.UserDetailsService 去进行验证
  • 到这里用过SS的都清楚了,只需要实现一个UserDetailService,写写下面这个方法就OK了:
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
到这里问题就出来了 :

这个方法只有一个参数,怎么才能传递多个参数呢?


一个可用的解决方案

重新自定义一个authentication provider,替换掉默认的DaoAuthenticationProvider.

先看看XML的配置:
Xml代码   收藏代码
  1. <authentication-manager alias="authenticationManager">  
  2.         <authentication-provider ref="loginAuthenticationProvider">  
  3.         </authentication-provider>  
  4.     </authentication-manager>  
  5.   
  6.     <bean id="loginAuthenticationProvider"  
  7.         class="com.XXX.examples.security.LoginAuthenticationProvider">  
  8.         <property name="userDetailsService" ref="loginUserDetailService"></property>  
  9.     </bean>  
 

这里我们依然仿照DaoAuthenticationProvider,传递一个UserDetailService给它,下面看看其实现:


Java代码   收藏代码
  1. public class LoginAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider  
  2. {  
  3.   
  4.     // ~ Instance fields  
  5.     // ================================================================================================  
  6.   
  7.     private PasswordEncoder passwordEncoder = new PlaintextPasswordEncoder();  
  8.   
  9.     private SaltSource saltSource;  
  10.   
  11.     private LoginUserDetailsService userDetailsService;  
  12.   
  13.     // ~ Methods  
  14.     // ========================================================================================================  
  15.   
  16.     protected void additionalAuthenticationChecks(UserDetails userDetails,  
  17.                                                   UsernamePasswordAuthenticationToken authentication)  
  18.             throws AuthenticationException  
  19.     {  
  20.         Object salt = null;  
  21.   
  22.         if (this.saltSource != null)  
  23.         {  
  24.             salt = this.saltSource.getSalt(userDetails);  
  25.         }  
  26.   
  27.         if (authentication.getCredentials() == null)  
  28.         {  
  29.             logger.debug("Authentication failed: no credentials provided");  
  30.   
  31.             throw new BadCredentialsException("Bad credentials:" + userDetails);  
  32.         }  
  33.   
  34.         String presentedPassword = authentication.getCredentials().toString();  
  35.   
  36.         if (!passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt))  
  37.         {  
  38.             logger.debug("Authentication failed: password does not match stored value");  
  39.   
  40.             throw new BadCredentialsException("Bad credentials:" + userDetails);  
  41.         }  
  42.     }  
  43.   
  44.     protected void doAfterPropertiesSet() throws Exception  
  45.     {  
  46.         Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");  
  47.     }  
  48.   
  49.     protected PasswordEncoder getPasswordEncoder()  
  50.     {  
  51.         return passwordEncoder;  
  52.     }  
  53.   
  54.     protected SaltSource getSaltSource()  
  55.     {  
  56.         return saltSource;  
  57.     }  
  58.   
  59.     protected LoginUserDetailsService getUserDetailsService()  
  60.     {  
  61.         return userDetailsService;  
  62.     }  
  63.   
  64.     protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)  
  65.             throws AuthenticationException  
  66.     {  
  67.         UserDetails loadedUser;  
  68.   
  69.         try  
  70.         {  
  71.             String password = (String) authentication.getCredentials();  
  72.             loadedUser = getUserDetailsService().loadUserByUsername(username, password);//区别在这里  
  73.         }  
  74.         catch (UsernameNotFoundException notFound)  
  75.         {  
  76.             throw notFound;  
  77.         }  
  78.         catch (Exception repositoryProblem)  
  79.         {  
  80.             throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);  
  81.         }  
  82.   
  83.         if (loadedUser == null)  
  84.         {  
  85.             throw new AuthenticationServiceException(  
  86.                                                      "UserDetailsService returned null, which is an interface contract violation");  
  87.         }  
  88.         return loadedUser;  
  89.     }  
  90.   
  91.     /** 
  92.      * Sets the PasswordEncoder instance to be used to encode and validate 
  93.      * passwords. If not set, the password will be compared as plain text. 
  94.      * <p> 
  95.      * For systems which are already using salted password which are encoded 
  96.      * with a previous release, the encoder should be of type 
  97.      * {@code org.springframework.security.authentication.encoding.PasswordEncoder} 
  98.      * . Otherwise, the recommended approach is to use 
  99.      * {@code org.springframework.security.crypto.password.PasswordEncoder}. 
  100.      * 
  101.      * @param passwordEncoder 
  102.      *            must be an instance of one of the {@code PasswordEncoder} 
  103.      *            types. 
  104.      */  
  105.     public void setPasswordEncoder(Object passwordEncoder)  
  106.     {  
  107.         Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");  
  108.   
  109.         if (passwordEncoder instanceof PasswordEncoder)  
  110.         {  
  111.             this.passwordEncoder = (PasswordEncoder) passwordEncoder;  
  112.             return;  
  113.         }  
  114.   
  115.         if (passwordEncoder instanceof org.springframework.security.crypto.password.PasswordEncoder)  
  116.         {  
  117.             final org.springframework.security.crypto.password.PasswordEncoder delegate = (org.springframework.security.crypto.password.PasswordEncoder) passwordEncoder;  
  118.             this.passwordEncoder = new PasswordEncoder()  
  119.             {  
  120.                 private void checkSalt(Object salt)  
  121.                 {  
  122.                     Assert.isNull(salt, "Salt value must be null when used with crypto module PasswordEncoder");  
  123.                 }  
  124.   
  125.                 public String encodePassword(String rawPass, Object salt)  
  126.                 {  
  127.                     checkSalt(salt);  
  128.                     return delegate.encode(rawPass);  
  129.                 }  
  130.   
  131.                 public boolean isPasswordValid(String encPass, String rawPass, Object salt)  
  132.                 {  
  133.                     checkSalt(salt);  
  134.                     return delegate.matches(rawPass, encPass);  
  135.                 }  
  136.             };  
  137.   
  138.             return;  
  139.         }  
  140.   
  141.         throw new IllegalArgumentException("passwordEncoder must be a PasswordEncoder instance");  
  142.     }  
  143.   
  144.     /** 
  145.      * The source of salts to use when decoding passwords. <code>null</code> is 
  146.      * a valid value, meaning the <code>DaoAuthenticationProvider</code> will 
  147.      * present <code>null</code> to the relevant <code>PasswordEncoder</code>. 
  148.      * <p> 
  149.      * Instead, it is recommended that you use an encoder which uses a random 
  150.      * salt and combines it with the password field. This is the default 
  151.      * approach taken in the 
  152.      * {@code org.springframework.security.crypto.password} package. 
  153.      * 
  154.      * @param saltSource 
  155.      *            to use when attempting to decode passwords via the 
  156.      *            <code>PasswordEncoder</code> 
  157.      */  
  158.     public void setSaltSource(SaltSource saltSource)  
  159.     {  
  160.         this.saltSource = saltSource;  
  161.     }  
  162.   
  163.     public void setUserDetailsService(LoginUserDetailsService userDetailsService)  
  164.     {  
  165.         this.userDetailsService = userDetailsService;  
  166.     }  
  167. }  
 
代码跟DaoAuthenticationProvider几乎一样,只是我们替换了UserDetailService,使用自定义的一个新的LoginUserDetailService:

Java代码   收藏代码
  1. public interface LoginUserDetailsService  
  2. {  
  3.     /** 
  4.      * 功能描述:根据用户米密码验证用户信息 
  5.      * <p> 
  6.      * 前置条件: 
  7.      * <p> 
  8.      * 方法影响: 
  9.      * <p> 
  10.      * Author , 2012-9-26 
  11.      * 
  12.      * @since server 2.0 
  13.      * @param username 
  14.      * @param password 
  15.      * @return 
  16.      * @throws UsernameNotFoundException 
  17.      */  
  18.     UserDetails loadUserByUsername(String username, String password) throws UsernameNotFoundException;  
  19. }  
 
一个简单的实现LoginUserDetailsServiceImpl:

Java代码   收藏代码
  1. public class LoginUserDetailsServiceImpl implements LoginUserDetailsService  
  2. {  
  3.   
  4.     private UserAccountService userAccountService;  
  5.   
  6.     /** 
  7.      * 
  8.      */  
  9.     public LoginUserDetailsServiceImpl()  
  10.     {  
  11.     }  
  12.   
  13.     /** 
  14.      * getter method 
  15.      * 
  16.      * @see LoginUserDetailsServiceImpl#userAccountService 
  17.      * @return the userAccountService 
  18.      */  
  19.     public UserAccountService getUserAccountService()  
  20.     {  
  21.         return userAccountService;  
  22.     }  
  23.   
  24.     /** 
  25.      * 功能描述:查找登录的用户 
  26.      * <p> 
  27.      * 前置条件: 
  28.      * <p> 
  29.      * 方法影响: 
  30.      * <p> 
  31.      * Author , 2012-9-26 
  32.      * 
  33.      * @since server 2.0 
  34.      * @param username 
  35.      * @return 
  36.      */  
  37.     public UserDetails loadUserByUsername(String username, String password) throws UsernameNotFoundException  
  38.     {  
  39.         boolean result = userAccountService.validate(username, password);  
  40.         if (!result)  
  41.         {  
  42.             return null;  
  43.         }  
  44.   
  45.         LoginUserDetailsImpl user = new LoginUserDetailsImpl(username, password);  
  46.         return user;  
  47.     }  
  48.   
  49.     /** 
  50.      * setter method 
  51.      * 
  52.      * @see LoginUserDetailsServiceImpl#userAccountService 
  53.      * @param userAccountService 
  54.      *            the userAccountService to set 
  55.      */  
  56.     public void setUserAccountService(UserAccountService userAccountService)  
  57.     {  
  58.         this.userAccountService = userAccountService;  
  59.     }  
  60.   
  61. }  
 
其他相关的代码:
GrantedAuthorityImpl
Java代码   收藏代码
  1. public class GrantedAuthorityImpl implements GrantedAuthority  
  2. {  
  3.   
  4.     /** 
  5.      * ROLE USER 权限 
  6.      */  
  7.     private static final String ROLE_USER = "ROLE_USER";  
  8.   
  9.     /** 
  10.      * Serial version UID 
  11.      */  
  12.     private static final long serialVersionUID = 1L;  
  13.   
  14.     private UserDetailsService delegate;  
  15.   
  16.     public GrantedAuthorityImpl(UserDetailsService user)  
  17.     {  
  18.         this.delegate = user;  
  19.     }  
  20.   
  21.     public String getAuthority()  
  22.     {  
  23.         return ROLE_USER;  
  24.     }  
  25.   
  26. }  
 
LoginUserDetailsImpl
Java代码   收藏代码
  1. public class LoginUserDetailsImpl extends User implements UserDetails  
  2. {  
  3.     /** 
  4.      * 
  5.      */  
  6.     private static final long serialVersionUID = -5424897749887458053L;  
  7.   
  8.     /** 
  9.      * 邮箱 
  10.      */  
  11.     private String mail;  
  12.   
  13.     /** 
  14.      * @param username 
  15.      * @param password 
  16.      * @param enabled 
  17.      * @param accountNonExpired 
  18.      * @param credentialsNonExpired 
  19.      * @param accountNonLocked 
  20.      * @param authorities 
  21.      */  
  22.     public LoginUserDetailsImpl(String username, String password, boolean enabled, boolean accountNonExpired,  
  23.                                 boolean credentialsNonExpired, boolean accountNonLocked,  
  24.                                 Collection<? extends GrantedAuthority> authorities)  
  25.     {  
  26.         super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);  
  27.     }  
  28.   
  29.     /** 
  30.      * @param username 
  31.      * @param password 
  32.      * @param authorities 
  33.      */  
  34.     public LoginUserDetailsImpl(String username, String password, Collection<? extends GrantedAuthority> authorities)  
  35.     {  
  36.         super(username, password, authorities);  
  37.     }  
  38.   
  39.     /** 
  40.      * @param username 
  41.      * @param password 
  42.      * @param authorities 
  43.      */  
  44.     public LoginUserDetailsImpl(String username, String password)  
  45.     {  
  46.         super(username, password, new ArrayList<GrantedAuthority>());  
  47.     }  
  48.   
  49.     /** 
  50.      * getter method 
  51.      * @see LoginUserDetailsImpl#mail 
  52.      * @return the mail 
  53.      */  
  54.     public String getMail()  
  55.     {  
  56.         return mail;  
  57.     }  
  58.   
  59.     /** 
  60.      * setter method 
  61.      * @see LoginUserDetailsImpl#mail 
  62.      * @param mail the mail to set 
  63.      */  
  64.     public void setMail(String mail)  
  65.     {  
  66.         this.mail = mail;  
  67.     }  
  68.   
  69.     @Override  
  70.     public String toString()  
  71.     {  
  72.         return super.toString() + "; Mail: " + mail;  
  73.     }  
  74.   
  75. }  
 
至于
<bean id="userAccountService"
        class="com.XXX.UserAccountService"/>
它的实现就随你的意吧,这里是模仿第三方的一个实现。

小结

为了自定义一个authenticationProvider,我们还需要自定义一个UserDetailsService,只需要这2个类,就实现了对验证参数的扩展了。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值