gpt4 book ai didi

java - Spring:从 SecurityContextHolder 获取自定义用户对象

转载 作者:行者123 更新时间:2023-12-02 13:16:19 27 4
gpt4 key购买 nike

我尝试实现存储所有登录的日志文件。

到目前为止,我在 LoginHandler 中添加了一些代码,但总是收到错误:

org.springframework.security.core.userdetails.User cannot be cast to at.qe.sepm.asn_app.models.UserData

我的 LoginHandler 中的方法:

@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
UserData user = (UserData)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

AuditLog log = new AuditLog(user.getUsername() + " [" + user.getUserRole() + "]" ,"LOGGED IN", new Date());
auditLogRepository.save(log);

handle(httpServletRequest, httpServletResponse, authentication);
clearAuthenticationAttributes(httpServletRequest);
}

是否可以将返回值类型从 SecurityContextHolder 更改为我的 UserData 对象?

附加代码:

public class MyUserDetails implements UserDetails {

private UserData user;

public UserData getUser(){
return user;
}

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

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

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

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

@Override
public boolean isEnabled() {
return false;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}

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

}

MyUserDetails myUserDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserData user = myUserDetails.getUser();

编译器表示 UserDetailsMyUserDetails 是不兼容的类型。

我的网络安全配置:

@Configuration
@EnableWebSecurity()
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;

@Override
protected void configure(HttpSecurity http) throws Exception {

http.csrf().disable();

http.headers().frameOptions().disable(); // needed for H2 console

http.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.invalidateHttpSession(false)
.logoutSuccessUrl("/login.xhtml");

http.authorizeRequests()
//Permit access to the H2 console
.antMatchers("/h2-console/**").permitAll()
//Permit access for all to error pages
.antMatchers("/error/**")
.permitAll()
// Only access with admin role
.antMatchers("/admin/**")
.hasAnyAuthority("ADMIN")
//Permit access only for some roles
.antMatchers("/secured/**")
.hasAnyAuthority("ADMIN", "EMPLOYEE", "PARENT")
//If user doesn't have permission, forward him to login page
.and()
.formLogin()
.loginPage("/login.xhtml")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/secured/welcome.xhtml").successHandler(successHandler());
// :TODO: user failureUrl(/login.xhtml?error) and make sure that a corresponding message is displayed

http.exceptionHandling().accessDeniedPage("/error/denied.xhtml");

http.sessionManagement().invalidSessionUrl("/error/invalid_session.xhtml");

}

@Bean
public AuthenticationSuccessHandler successHandler() {
return new LoginHandler();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//Configure roles and passwords via datasource
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username, password, true from user_data where username=?")
.authoritiesByUsernameQuery("select username, user_role from user_data where username=?")
.passwordEncoder(passwordEncoder());
}

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

我还尝试实现 Springs UserUserDetailsUserDetailsS​​ervice 但到目前为止我失败了。我不知道如何将这些调整到我的项目,因为我使用继承。我的模型是 UserData ,它继承于 ParentEmployee。所以我还有 UserBaseRepositoryUserDataRepository。这些都让我很困惑。

现在我坚持实现 Spring 提供的用户类中的方法。

最佳答案

org.springframework.security.core.UserDetails 应始终由您自己的 UserData 或包装您的 UserData 实例的另一个类实现

例如:

public class UserData{
private username;
private password;
/// other user parameters
.
.
etc
}

public class MyUserDetails implements UserDetails {

private UserData user;

public UserData getUser(){
return user;
}

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

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

}

然后你像这样转换它

MyUserDetails myUserDetails = (MyUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

UserData user = myUserDetails.getUser();

关于java - Spring:从 SecurityContextHolder 获取自定义用户对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43757055/

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