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

时间:2017-05-03 10:08:32

标签: java spring spring-security

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

到目前为止,我将一些代码放到了我的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更改为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-classes方法。

1 个答案:

答案 0 :(得分:1)

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();