gpt4 book ai didi

java - Spring Boot 自定义用户并进行身份验证

转载 作者:行者123 更新时间:2023-12-02 03:04:47 25 4
gpt4 key购买 nike

我正在尝试使用我想要的属性进行自定义用户并使用身份验证,CustomUser扩展了spring User,用户由实现UsersDetailsS​​ervice的CustomProvider返回

@Service
@Qualifier("UserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

@Autowired
private UserRepository userRepository;

@Override
@Transactional
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user=userRepository.findByEmail(email);
return new CustomUser(user.getName(),user.getPassword(),buildUserAuthority(user.getRoles()));
}

private List<GrantedAuthority> buildUserAuthority(Set<Role> userRoles) {

Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

// add user's authorities
for (Role userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
}

List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);

return Result;
}


@Getter
@Setter
public class CustomUser extends User {

public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}

public String firstName;
public String lastName;
}


@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("UserDetailsService")
private UserDetailsService customUserDetailsService;


@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
/* auth.
jdbcAuthentication()
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource)
.passwordEncoder(bCryptPasswordEncoder);
*/
auth.userDetailsService(customUserDetailsService);
}
}

我有 2 个问题:

1-我对 auth.jdbcAuthentication 进行了评论,因为我无法让身份验证和 customProvider 一起工作,如何将数据库身份验证与 customuser 一起使用?

2-如果我评论 jdbcAuthentication ,则自定义用户可以工作,但是当我获得主体时,密码为空:authentication.getPrincipal().getPassword()

<小时/>

更新:

我已经通过eraseCredentials(false)解决了2个问题,但仍然无法同时执行这两个操作(使用自定义用户进行身份验证)

最佳答案

旧答案:

我已经解决了这个问题:

auth.eraseCredentials(false).userDetailsService(customUserDetailsService).and().jdbcAuthentication()
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource)
.passwordEncoder(bCryptPasswordEncoder);
<小时/>

更新:

我发现不需要使用两种类型的身份验证,因为 spring 会使用返回的用户验证密码。

关于java - Spring Boot 自定义用户并进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57029865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com