2016-11-10 62 views
0

我正在使用Spring Security,HTML和thymeleaf,並且我將檢索登錄失敗的用戶。登錄有兩步:第一步檢查用戶和密碼是否正確進入LDAP,第二步檢查用戶是否具有到數據庫中的角色。只有兩者都通過,用戶才能通過身份驗證。現在我想登錄失敗的用戶進入我的註冊頁面(預編譯輸入字段)。註冊頁面是accessDeniedPage。這是驗證:春季安全:如何檢索用戶名到accessDeniedPage?

public Authentication authenticate(Authentication authentication) throws AuthenticationException { 
      Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); 
      String name = authentication.getName(); 
      String password = authentication.getCredentials().toString(); 
      if (name == null || name.isEmpty() || password == null || password.isEmpty()) 
       return null; 
      boolean isFind = ldapServices.ldapSearch(name, password);       
      if (isFind){ 
       com.domain.User user = userServices.getByUsersEnabled(name); 
       if (user!=null){ 
        authorities.add(new SimpleGrantedAuthority("ROLE_"+user.getRole().getRole())); 
       } 
       return new UsernamePasswordAuthenticationToken(user, password, authorities); 
      }   
      else return null; 
     } 

和重定向是:

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    List<Role> roles=roleServices.getRoles(); 
    //Retrieve array of roles(only string field without id) 
    String[] rolesArray = new String[roles.size()]; 
    int i=0; 
    for (Role role:roles){ 
     rolesArray[i++] = role.getRole(); 
    } 

    http 
    .authorizeRequests() //Authorize Request Configuration 
    //the "/register" path are accepted without login 
    .antMatchers("/registration/**").authenticated() 
    //all the path need authentication 
    .anyRequest().hasAnyRole(rolesArray)//.authenticated() 
    .and()//Login Form configuration for all others 
    .formLogin() 
    .loginPage("/login") 
    .permitAll() 
    .and() 
    //redirect on page "registration" if user doens't exist in DART database 
    .exceptionHandling().accessDeniedPage("/registration") 
    .and() 
    .logout() 
    .logoutSuccessUrl("/login?logout") 
    .deleteCookies("JSESSIONID", "JSESSIONID") 
    .invalidateHttpSession(true) 
    .permitAll(); 
} 

如果我在/登記控制器添加主要爲null。爲什麼? 主體爲null,可能在驗證方法中有錯誤。此外,由於我的註冊Web服務未通過身份驗證,因此我可能遇到安全問題,而他們應該無任何身份驗證 登錄失敗的用戶是否有可能進入註冊頁面? 感謝

+0

在我看來,你最後一個問題的答案是肯定的。默認情況下,如果有任何用戶登錄,並且該用戶沒有訪問任何頁面,則可以從Principal獲得用戶的信息。 –

+0

主體返回null,我也嘗試過使用@AuthenticationPrincipal用戶用戶,並在HTML代碼中使用sec:authentication =「principal.username」,全部爲空 – luca

+0

我從您的安全conf中瞭解到,如果任何註冊用戶想要打開註冊頁面你想顯示你沒有訪問此頁面。這是真的嗎? –

回答

0

我已經改變了此行到身份驗證方法:因爲他根本不存在到數據庫中,以便查詢返回空對象,而不是我要創建只有一個用戶

return new UsernamePasswordAuthenticationToken(user==null?new User(name,null,false):user, password, authorities); 

用戶爲空用戶名。