我试图为当前登录的用户添加一些自定义数据,所以我发现可以实现自己的UserDetailsService并将其插入Spring中,但从未调用过,我总是将Principal用作用户名字符串。 / p>
我有UserDetailsService的实现:
game view
我对UserDetails的实现:
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
...
}
}
并尝试通过多种方式在config(SecurityConfiguration)中进行设置:
import org.springframework.security.core.userdetails.User;
public class LoggedInUser extends User {
...
}
或
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider customAuthProvider;
@Autowired
private UserDetailsService userDetailServiceImpl;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider);
auth.userDetailsService(userDetailServiceImpl).passwordEncoder(passwordService.getPasswordEncoder());
}
...
}
或
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider);
auth.userDetailsService(userDetailServiceImpl).passwordEncoder(passwordService.getPasswordEncoder());
}
无效,...我尝试过多种方式检索用户信息:
在使用中(我收到无效的转换错误):
身份验证身份验证= SecurityContextHolder.getContext()。getAuthentication(); (LoggedInUser)authentication.getPrincipal()
有人知道为什么它不起作用吗?我的impl类是否默认被其他地方覆盖?我试图查看日志(logging.level.org.springframework.security = TRACE),但没有运气:/ 我可以登录,效果很好,只是主体数据始终只是用户名String,而不是我的课程。
答案 0 :(得分:1)
ILya Cyclone的评论是找出问题所在的关键,再次检查CustomAuthenticationProvider
后,我注意到在返回数据时,您可以指定Principal
,而不仅仅是用户名,您可以在其中添加自定义UserDetails
,由于未调用该自定义UserDetailsService
,因此我以为总是调用该自定义错误。
因此,最终足以将自定义AuthenticationProvider
与自定义UserDetails
:
@Service
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserService userService;
@Autowired
private PasswordService passwordService;
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
String username = auth.getName();
String password = auth.getCredentials().toString();
User user = userService.getUserWithPermissionsByName(username);
if (user == null) {
throw new BadCredentialsException("invalid_username_or_pass");
}
if (!passwordService.passwordsMatch(password, user.getPassword())) {
throw new BadCredentialsException("invalid_username_or_pass");
}
String[] permissions = user.getPermissions().stream().map((p) -> p.getName()).toArray(String[]::new);
List<GrantedAuthority> grantedAuths = AuthorityUtils.createAuthorityList(permissions);
return new UsernamePasswordAuthenticationToken(new LoggedInUser(user.getName(), user.getPassword(), true, true, true, true, grantedAuths, user.getId()),
password, grantedAuths);
}
@Override
public boolean supports(Class<?> auth) {
return auth.equals(UsernamePasswordAuthenticationToken.class);
}
}