2015-12-02 30 views
0

我想設置我的用戶到我創建的課程對象,我不斷收到錯誤org.springframework.security.core.userdetails.User cannot be cast to com.example.security.CustomUserDetails我知道我得到會話中的用戶詳細信息,因爲當我在調試模式下運行它時,我可以看到當前登錄用戶的名稱,所以我認爲我有點接近解決方案。用戶不能轉換到com.example.security.CustomUserDetails春季安全

這裏是我的控制器

@RequestMapping(value="createCourse", method=RequestMethod.POST) 
public String createCoursePost (@ModelAttribute Course course, Long userId, ModelMap model, Authentication auth) 
{ 
    CustomUserDetails myUserDetails = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
    userId = myUserDetails.getUser().getId(); 

    User user = userRepo.findOne(userId); 

    course.setUser(user); 

    courseRepo.save(course); 


    return "redirect:/courses"; 
} 

這裏是我的UserDetailsS​​erviceImpl

@Service 
@Qualifier("customUserDetailsService") 
public class UserDetailsServiceImpl implements UserDetailsService { 

@Autowired 
private UserRepository userRepo; 

@Transactional 
@Override 
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 

    com.example.domain.User user = userRepo.findByUsername(username); 
    List<GrantedAuthority> authorities = buildUserAuthority(user.getRoles()); 

    return buildUserForAuthentication(user, authorities); 

} 

private User buildUserForAuthentication(com.example.domain.User user, 
             List<GrantedAuthority> authorities) { 
    return new User(user.getUsername(), user.getPassword(), authorities); 
} 

private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) { 

    Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>(); 

    // Build user's authorities 
    for (UserRole userRole : userRoles) { 
     setAuths.add(new SimpleGrantedAuthority(userRole.getRoleName())); 
    } 

    return new ArrayList<GrantedAuthority>(setAuths); 

} 

這裏是我的customUserDetails,它可能是我獲取和設置用戶可能是多餘的,但我看到了這樣的一個例子,所以我不確定該怎麼做。

public class CustomUserDetails extends User implements UserDetails{ 

private User user; 

public User getUser() { 
    return user; 
} 

public void setUser(User user) { 
    this.user = user; 
} 

private static final long serialVersionUID = 2020921373107176828L; 

public CustomUserDetails() {} 

public CustomUserDetails (User user) { 
    super(user); 
} 

@Override 
public Set<Authorities> getAuthorities() { 
    return super.getAuthorities(); 
} 
@Override 
public boolean isAccountNonExpired() { 
    return true; 
} 
@Override 
public boolean isAccountNonLocked() { 
    return true; 
} 
@Override 
public boolean isCredentialsNonExpired() { 
    return true; 
} 
@Override 
public boolean isEnabled() { 
    return true; 
} 
} 

這裏是我的webSecurityConfig

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

private static PasswordEncoder encoder; 

@Autowired 
private UserDetailsService customUserDetailsService; 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.csrf() 
    .csrfTokenRepository(csrfTokenRepository()); 

    http 
    .authorizeRequests() 
     .antMatchers("/", "/home", "/register", "/courses", "/editCourse", "/sets", "/search", "/viewCourse/{courseId}", "/fonts/glyphicons-halflings-regular.ttf","fonts/glyphicons-halflings-regular.woff", "fonts/glyphicons-halflings-regular.woff", "/viewCourse/post/{postId}").permitAll() 
     .anyRequest().authenticated(); 

    http 
    .formLogin() 
     .loginPage("/login") 
     .usernameParameter("username").passwordParameter("password") 
      .permitAll() 
      .and() 
     .logout() 
      .permitAll() 
      .logoutSuccessUrl("/loggedout") 
      .and() 
      .sessionManagement() 
       .maximumSessions(1); 


} 

@Override 
protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    auth.userDetailsService(customUserDetailsService) 
      .passwordEncoder(passwordEncoder()); 
} 

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

    return encoder; 
} 

private CsrfTokenRepository csrfTokenRepository() 
{ 
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); 
    repository.setSessionAttributeName("_csrf"); 
    return repository; 
} 
} 

回答

0

我解決了這個以防其他人看到這一點。我認爲我的問題是我沒有返回userdetailsimpl類中的userdetails。而且我還必須更新我的控制器。因此,這裏是我的新代碼

控制器

@RequestMapping(value="createCourse", method=RequestMethod.POST) 
public String createCoursePost (@ModelAttribute Course course, Long userId, ModelMap model) 
{ 
    CustomUserDetails myUserDetails = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
    userId = myUserDetails.getUser().getId(); 

    User user = userRepo.findOne(userId); 

    course.setUser(user); 

    courseRepo.save(course); 


    return "redirect:/courses"; 
} 

而且userDetailsS​​erviceImpl

@Service 
@Qualifier("customUserDetailsService") 
public class UserDetailsServiceImpl implements UserDetailsService { 

@Autowired 
private UserRepository userRepo; 

@Transactional 
@Override 
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 

    com.example.domain.User user = userRepo.findByUsername(username); 

    CustomUserDetails customUserDetails = new CustomUserDetails(user); 
    customUserDetails.setUser(user); 

    return customUserDetails; 
} 
}