Spring身份验证提供程序忽略我的详细信

时间:2013-11-13 08:10:19

标签: java spring

我在想,为什么我从来没有使用getDetails从Authentication对象中获取我的User对象。我只使用getPrincipal获取用户名。

调试我的项目我看到过一种我没想过的行为。

我使用Spring 3.2.4.RELEASE。

security-app-context.xml包含此配置

<authentication-manager alias="authenticationManager">
    <authentication-provider user-service-ref="userDetailsService">
        <password-encoder ref="passwordEncoder" />
    </authentication-provider>
</authentication-manager>

我的userDetailsS​​ervice就是这个

@Service
class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService, InitializingBean {
    @Override
    public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
        try {
            final User search = new User();
            search.setUsername(username);
            final User user = service.get(search, null);
            if (user != null) {
                UserDetailsModel model = new UserDetailsModel(user.getUsername(), user.getPassword(),
                    getGrantedAuthorities(user.getRoles()));
                model.setDetails(user);
                return model;
            }
        } catch (final Throwable th) {
            log.error("", th);
        }
        throw new UsernameNotFoundException("Bad credentials");
    }

可以看到,详细信息是使用我服务中的当前用户数据设置的。

从点开始调试,当它返回模型时,我们返回

org.springframework.security.authentication.dao.DaoAuthenticationProvider line 101
org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider line 132

在第二个类中,第190行中有一个方法createSuccessAuthentication,最终被执行。

protected Authentication createSuccessAuthentication(Object principal, Authentication authentication,
        UserDetails user) {
    // Ensure we return the original credentials the user supplied,
    // so subsequent attempts are successful even with encoded passwords.
    // Also ensure we return the original getDetails(), so that future
    // authentication events after cache expiry contain the details
    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal,
            authentication.getCredentials(), authoritiesMapper.mapAuthorities(user.getAuthorities()));
    result.setDetails(authentication.getDetails());

    return result;
}

在第198行中,它为结果添加了详细信息(身份验证),但它不会从提供的UserDetails中获取,而是从身份验证中获取,但不包含详细信息。

这是配置问题,我的错还是Spring中的错误?

1 个答案:

答案 0 :(得分:1)

getPrincipal()方法返回UserDetails的实现,而不是getDetails()方法。