如何在Spring Security 3中实现自定义身份验证?


问题内容

我知道这个问题已经回答了很多次,但是我很困惑。我的应用程序中已经有一个身份验证机制,我只想使用Spring MVC的授权部分。我正在使用Spring MVC
3和Spring Security 3。

当我在Internet上搜索时,发现了两个解决方案,第一个是仅实现AuthenticationProvider接口。例子1。第二个是实现Example2的
UserDetails和UserDetailsS​​ervice,所以我在这里迷路了。

-—更新----


问题答案:

在大多数情况下,仅使用用户名和密码进行身份验证并使用角色进行授权时,实现自己的UserDetailsS​​ervice就足够了。

用户名密码验证的流程通常如下:

  • Spring安全过滤器(基本身份验证/表单/ ..)选择用户名和密码,将其转换为UsernamePasswordAuthentication对象,并将其传递给AuthenticationManager
  • 身份验证管理器寻找可以处理UsernamePasswordtokens的候选提供程序,在本例中为DaoAuthenticationProvider并将令牌传递给进行身份验证
  • 身份验证提供程序调用方法loadUserByUsername接口,如果用户不存在,则抛出UsernameNotFound异常,或者返回包含用户名,密码和权限的UserDetails对象。
  • 然后,身份验证提供程序将提供的UsernamePasswordToken和UserDetails对象的密码进行比较。(它也可以通过PasswordEncoders处理密码哈希)。如果不匹配,则身份验证失败。如果匹配,则注册用户详细信息对象,并将其传递给AccessDecisionManager,后者执行授权部分。

因此,如果DaoAuthenticationProvider中的验证适合您的需求。然后,您只需要实现自己的UserDetailsS​​ervice并调整DaoAuthenticationProvider的验证即可。

使用spring 3.1的UserDetailsS​​ervice的示例如下:

springXML:

<security:authentication-manager>
     <security:authentication-provider user-service-ref="myUserDetailsService" />
</security:authentication-manager>

<bean name="myUserDetailsService" class="x.y.MyUserDetailsService" />

UserDetailsS​​ervice实现:

public MyUserDetailsService implements UserDetailsService {

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //Retrieve the user from wherever you store it, e.g. a database 
    MyUserClass user = ...; 
    if (user == null) {
        throw new UsernameNotFoundException("Invalid username/password.");
    }
    Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("Role1","role2","role3");
    return new User(user.getUsername(), user.getPassword(), authorities);
}

}