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

到目前为止,我在LoginHandler中放入了一些代码,但始终收到错误消息:


  org.springframework.security.core.userdetails。不能将用户强制转换为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是不兼容的类型。

我的WebSecurityConfig:

@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 UserUserDetailsUserDetailsService,但是到目前为止,我还是失败了。我不知道如何根据我的项目来调整它们,因为我使用继承。我的模型是UserData,它继承了ParentEmployee。所以我也有UserBaseRepositoryUserDataRepository。这些都让我很困惑。

现在,我坚持从Spring提供的User-classs实现方法。

最佳答案

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/

10-13 09:47