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

Java Spring:从SecurityContextHolder获取自定义用户对象,java,spring,spring-security,Java,Spring,Spring Security,我尝试实现存储所有登录的日志文件 到目前为止,我在我的LoginHandler中添加了一些代码,但我总是得到错误: org.springframework.security.core.userdetails.User不能强制转换为at.qe.sepm.asn_app.models.UserData 我的LoginHandler中的方法: @Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequ

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

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

org.springframework.security.core.userdetails.User不能强制转换为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更改为my 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();
}
编译器说UserDetails和MyUserDetails是不兼容的类型

我的网站安全配置:

@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用户、UserDetails和UserDetails服务,但到目前为止我失败了。我不知道如何调整这些到我的项目,因为我使用继承。我的模型是继承给父级和雇员的UserData。所以我还有UserBaseRepository和UserDataRepository。这些都让我很困惑

现在,我坚持实现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();

我仍然收到一个不兼容的错误。。我在上面添加了代码。。当我在UserDataNo中使用@Entity这样的注释时,它有什么区别吗?@Entity不相关here@SteveOhio我想我已经修复了不兼容类型的错误。具体错误是什么​ 你得到的是什么?只需从上面得到错误消息。我试图实现userdetails等等,但我未能使自定义userdetails实现变得有用。您还必须实现userdetails服务。该服务应该是什么样子。。实现UserDetailsRepository等等?我也使用继承。。所以我有一个UserBaseRepository和一个UserRepository。。那么,我的UserDetailsService应该实现什么存储库呢?
MyUserDetails myUserDetails = (MyUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

UserData user = myUserDetails.getUser();