2017-03-22 102 views
0

我知道如果將它作爲方法參數包含在內,Spring會將主體傳遞給控制器​​的方法。Spring Security - 實現UserDetailsS​​ervice

我試圖通過實施UserDetailsService擴展這個功能:

我創建了一個名爲CustomUserDetails類,它擴展org.springframework.security.core.userdetails.User

我創建了一個名爲CustomUserDetailsService服務實現UserDetailsService

異常

HTTP狀態500 - 請求處理失敗;嵌套的異常是 java.lang.ClassCastException: org.springframework.security.authentication.UsernamePasswordAuthenticationToken 不能轉換到com.demo.model.CustomUserDetails

在我的控制器方法下面的行拋出異常:

CustomUserDetails userDetails = (CustomUserDetails) principal; 

Controller.java

@RequestMapping(value = "/dashboard", method = RequestMethod.GET) 
    public ModelAndView displayHomePage(ModelAndView modelAndView, Principal principal, HttpServletRequest request) { 

     // Throws exception here 
     CustomUserDetails userDetails = (CustomUserDetails) principal;  

     System.out.println(userDetails.getFirstName()); 

     // Tried this and it also throws exception 
     // User cannot be cast to CustomUserDetails 
     //Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
     //CustomUserDetails userDetails = (CustomUserDetails)auth.getPrincipal(); 

     // Render template located at 
     // src/main/resources/templates/dashboard.html 
     modelAndView.setViewName("dashboard"); 

     return modelAndView; 
    } 

SecurityConfiguration.java

@Configuration 
@EnableWebSecurity 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private BCryptPasswordEncoder bCryptPasswordEncoder; 

    @Autowired 
    private DataSource dataSource; 

    @Value("${spring.queries.users-query}") 
    private String usersQuery; 

    @Value("${spring.queries.roles-query}") 
    private String rolesQuery; 

    @Autowired 
    SecurityHandler successHandler; 

    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery) 
       .dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder); 
    } 


    @Override 
    protected void configure(HttpSecurity http) throws Exception { 

     http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/register*").permitAll() 
       .antMatchers("/reset").permitAll().antMatchers("/forgot").permitAll().antMatchers("/grid").permitAll() 
       .antMatchers("/login").permitAll().antMatchers("/admin/**").hasAuthority("ADMIN").anyRequest() 
       .authenticated().and().formLogin().loginPage("/login").failureUrl("/login?error") 
       .defaultSuccessUrl("/dashboard").successHandler(successHandler).usernameParameter("email") 
       .passwordParameter("password").and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")) 
       .logoutSuccessUrl("/login?logout").and().exceptionHandling().accessDeniedPage("/access-denied"); 

    } 

    @Override 
    public void configure(WebSecurity web) throws Exception { 
     web.ignoring().antMatchers("/error**", "/resources/**", "/static/**", "/css/**", "/js/**", "/img/**"); 
    } 

} 

CustomUserDetails.java

public class CustomUserDetails extends org.springframework.security.core.userdetails.User { 

    public CustomUserDetails(String username, String password, 
     Collection<? extends GrantedAuthority> authorities) {    
     super(username, password, authorities); 
    } 

    private String firstName; 
    private String lastName; 


    public String getFirstName() { 
     return firstName; 
    } 

    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 

    public String getLastName() { 
     return lastName; 
    } 

    public void setLastName(String lastName) { 
     this.lastName = lastName; 
    } 

} 

CustomUserDetailsS​​ervice.java

@Service 
public class CustomUserDetailsService implements UserDetailsService{ 

    @Override 
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException{   

     if(StringUtils.isEmpty(userName)) 
      throw new UsernameNotFoundException("User name is empty"); 

     //if you don't use authority based security, just add empty set 
     Set<GrantedAuthority> authorities = new HashSet<>(); 
     CustomUserDetails userDetails = new CustomUserDetails(userName, "", authorities);    

     userDetails.setFirstName("Testing: " + new Date()); 


     return userDetails; 
    } 

} 
+0

的'Principal'你得到的是'Authentication'對象,而不是你的用戶。在那你可以調用'getPrincipal'來獲得實際的用戶。 (這也是類拋出異常告訴你的)。 –

+0

你可以發佈實際拋出異常的代碼嗎? – rptmat57

+0

@ rptmat57當然我添加了控制器方法代碼 –

回答

0

WebSecurityConfigurerAdapter,您需要添加您註冊自定義座標AIL服務:

auth.userDetailsService(customDetailService)

 @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery) 
       .dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder); 
    } 
相關問題