我尝试实现存储所有登录的日志文件。
到目前为止,我将一些代码放到了我的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();
编译器说UserDetails
和MyUserDetails
是不兼容的类型。
我的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 User
,UserDetails
和UserDetailsService
,但到目前为止我失败了。我不知道如何将这些调整到我的项目,因为我使用继承。我的模型UserData
继承到Parent
和Employee
。所以我也有UserBaseRepository
和UserDataRepository
。这些都让我很困惑。
目前我一直在实现Spring提供的User-classes方法。
答案 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();