gpt4 book ai didi

java - Spring 在 SecurityContextHolder 中获取自定义 UserDetails

转载 作者:行者123 更新时间:2023-11-30 10:37:58 27 4
gpt4 key购买 nike

我在我的网络项目中使用 SpringSecurity。我有保存在数据库中的实体用户。我需要使用用户 ID 在 BD 中执行请求,以从该 BD 中的其他表获取任何信息。在 Spring Security 中进行身份验证后,如何从 SecurityContextHolder 获取我的用户而不是标准 Spring 用户(此用户没有 ID)?

 @Entity
@Table(name = "users")
public class User{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Column(name = "name")
private String name;

@Column(name = "login")
private String login;

@Column(name = "password")
private String password;

+ getters and setters

PS.对不起我的英语:)

最佳答案

您将在另一个类中实现 UserDetailsS​​ervice 接口(interface)和 UserDetails 接口(interface)。例如:

自定义用户详细信息服务:

@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
// your UserRepository for your user
private final UserRepository userRepository;

@Autowired
public CustomUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}


@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (null == user || ! user.getUsername().equals(username)) {
throw new UsernameNotFoundException("No user present with username: " + username);
} else {

return new CustomUserDetails(user);
}
}
}

自定义用户详细信息:

// You want to extend your User class here
public class CustomUserDetails extends User implements UserDetails {
private static final long serialVersionUID = 1L;
private Users user;

public CustomUserDetails(User user) {
super(user);
this.user = user;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
// You don't talk about UserRoles, so return ADMIN for everybody or implement roles.
return AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN");
}

@Override
public boolean isAccountNonExpired() {
return true;
}

@Override
public boolean isAccountNonLocked() {
return true;
}

@Override
public boolean isCredentialsNonExpired() {
return true;
}

@Override
public boolean isEnabled() {
// just for example
return this.user.getActive() == true;
}

@Override
public String getUsername() {
return this.user.getUsername();
}

@Override
public String getPassword() {
return this.user.getPassword();
}

// Just an example to put some addititional Data to your logged in user

public String getUserDatabase() {
return "usertable" + Integer.toString(1 + this.user.getUserId());
}


}

在您的 User 类中,为 hibernate 创建一个空的构造函数,并使用一个 User 实例:

@Entity
@Table(name = "users")
public class User{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Column(name = "name")
private String name;

@Column(name = "login")
private String login;

@Column(name = "password")
private String password;

public User() {}

public User(User user) {
this.id = user.getId();
this.name = user.getName();
// … the same for all properties.
}
}

在您的 WebSecurityConfig 中,@Autowire CustomUserDetailsS​​ervice 并将其注入(inject)到身份验证流程中:

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final
UserDetailsService service;

@Autowired
public WebSecurityConfig(UserDetailsService service) {
this.service = service;
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(service).passwordEncoder(passwordEncoder());

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
//left out because not related here
}
}

就是这样。您现在可以在每个 Controller 或提供程序中将经过身份验证的主体转换为您的 CustomUserDetails:

CustomUserDetails userDetails = 
(CustomUserDetails) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal();

关于java - Spring 在 SecurityContextHolder 中获取自定义 UserDetails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39930876/

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