2017-02-17 69 views
0

我試圖完成一些非常簡單的事情,我確信一旦我得到這個,我會稱自己爲驢。但是,以下是我嘗試在sudo代碼中執行的步驟。Spring安全驗證webservice並從數據庫檢索角色

step1 
--get username and password from login form 

step2 
-- send username and password to web service 

step3 
-- if the return from the service equals "N" show error else if the return from the service equals "Y" then authenticate a user and query database for user roles. 

step4 
-- if the user role is not allowed to see page show error page else continue to page. 

我試了幾個教程,我只是失敗悲慘。我懷疑是因爲我看過的所有內容都是與配置相關的或與註釋相關的,所以我很難理解用戶在什麼時候進行身份驗證。

我已經試過

http://www.ekiras.com/2016/04/authenticate-user-with-custom-user-details-service-in-spring-security.html

http://o7planning.org/en/10603/spring-mvc-security-and-spring-jdbc-tutorial Spring security access with multiple roles

我最大的問題是上面第三步。我怎樣才能做到這一點?我只是不明白如何驗證用戶並向該用戶添加若干角色,以保持在spring的constratint中。

+0

您的Web服務只返回Y和N的成功和失敗嗎?如果是的話,那麼很難推斷出你想返回給客戶端的錯誤,比如用戶不存在,用戶憑證無效或者用戶在數據庫中不活躍,理想情況下,Web服務應該返回適​​當的響應以及用戶數據(至少是角色)這樣你就不需要再次查詢數據庫來獲取角色。 – Apollo

+0

感謝阿波羅的迴應。如果服務響應等於「n」,則返回「錯誤的用戶名/密碼」錯誤。所以我真正的問題在上面的第3步。我認爲,但我不確定,是否需要以某種方式使用用戶詳細信息服務,但我不確定自己在做什麼。 – Miguel

+0

@Miguel,但你使用彈簧安全嗎?因爲如果你正在使用它,你不需要web服務,你必須添加你的UserDetailsS​​ervice的實現 – cralfaro

回答

1

當你使用Spring的安全,你可以用這個結構:

[我這種情況是基於註解與Spring的引導。]

您將需要從WebSecurityConfigurerAdapter

延伸的ApplicationSecurity類
public class ApplicationSecurity extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private UserDetailSecurityService userDetailSecurityService; 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.csrf().disable().authorizeRequests().antMatchers("/static").permitAll().anyRequest() 
       .fullyAuthenticated(); 

     http 
       .csrf().disable() 
       .formLogin().loginPage("/login").failureUrl("/login?error=1") 
       .permitAll().defaultSuccessUrl("/") 
       .successHandler(
         new NoRedirectSavedRequestAwareAuthenticationSuccessHandler()) 
       .and() 
        .sessionManagement() 
        .sessionAuthenticationErrorUrl("/notauthorized") 
        .invalidSessionUrl("/notauthorized") 
       .and() 
        .logout() 
        .deleteCookies("JSESSIONID", "SESSION") 
       .permitAll(); 
    } 

    //If you want to add some encoder method to store your passwords 
    @Override 
    public void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth.userDetailsService(userDetailSecurityService).passwordEncoder(passwordEncoder()); 
    } 


    @Bean 
    public PasswordEncoder passwordEncoder(){ 
     return new MD5PasswordEncoder(); 
    } 


    private class NoRedirectSavedRequestAwareAuthenticationSuccessHandler extends 
      SimpleUrlAuthenticationSuccessHandler { 

     final Integer SESSION_TIMEOUT_IN_SECONDS = 30 * 60; /** 30 min */ 

     @Override 
     public void onAuthenticationSuccess(HttpServletRequest request, 
              HttpServletResponse response, Authentication authentication) 
       throws ServletException, IOException { 

      request.getSession().setMaxInactiveInterval(SESSION_TIMEOUT_IN_SECONDS); 
      response.sendRedirect("/"); 
     } 
    } 
} 

你的類UserDetailsS​​ecurityService一定要實現的UserDetailsS​​ervice,這是一個Spring Security類,需要覆蓋的方法loadUserByUsername()

@Service 
public class UserDetailSecurityService implements UserDetailsService{ 

    @Autowired 
    UserService userService; 

    @Override 
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 
     /*Here in your case would call your WebService and check if the result is Y/N and return the UserDetails object with all roles, etc 
     If the user is not valid you could throw an exception 
     */ 
     return userService.findByUsername(username); 
    } 
}