JavaSpring身份验证提供程序忽略我的详细信息
我想知道,为什么我从来没有使用getDetails从身份验证对象获取我的用户对象。我仅使用getPrincipal获取用户名
在调试我的项目时,我看到了一种我没有预料到的行为
我使用Spring 3.2.4。释放
安全应用程序上下文。xml包含此配置
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsService">
<password-encoder ref="passwordEncoder" />
</authentication-provider>
</authentication-manager>
我的UserDetails服务是这样的
@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 楼答案
getPrincipal()方法返回UserDetails的实现,而不是getDetails()方法