2016-12-25 188 views
0

我有一個基於Spring構建的Web服務。我目前正在驗證使用Spring Security的如下:Spring Security的授權和身份驗證

@Configuration 
@EnableGlobalMethodSecurity(securedEnabled=true) 
@EnableWebSecurity 

public class ServerSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private Properties properties; 

    private static final String ALL_URI = "/v1/**"; 
    private static final String HEALTH_URI = "/v1/healthCheck"; 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.addFilterBefore(getFilter(), BasicAuthenticationFilter.class); 
     http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 
     http.authorizeRequests() 
       .antMatchers(HEALTH_URI).permitAll() 
       .anyRequest().authenticated(); 
     http.csrf().disable(); 
    } 

    private AuthenticationFilter getFilter() { 
     return new AuthenticationFilter(properties.getKey()); 
    } 
} 

AuthenticationFilter類擴展AbstractAuthenticationProcessingFilter和執行實際的驗證。如果我想將授權添加到我的安全性中,我是否只需在AuthenticationFilter的attemptAuthentication方法中進行這些檢查?還是有更好的方法來做到這一點?我理解的方式是授權和認證應該獨立完成。您首先進行身份驗證,然後驗證權限。所以,我會假設在Spring Security中會有更好的方法來進行授權,而不是將其添加到attemptAuthentication方法中。

回答

0

你需要一個AuthenticationProvider做身份驗證,實現AuthenticationProvider並覆蓋authenticationsupports方法,然後注入到AuthenticationManager。在過濾器

attemptAuthentication方法通常是讓authentication(例如UsernamePasswordFilter獲取從請求usernamepassword,然後生成一個UsernamePasswordAuthenticationTokenAuthenticationManager

supports方法測試AuthenticationProvider是否可以用來做驗證。(例如DaoAuthenticationProvider支持UsernamePasswordAuthenticationToken

authenticate方法用於進行身份驗證(例如,DaoAuthenticationProvider通過用戶名獲取真實密碼,然後與用戶比較輸入),則此方法應返回已經過身份驗證的Authentication(例如UsernamePasswordAuthenticationToken),並且此身份驗證應包含用戶權限(可用於hasRole('xxx'))或使用詳細信息等。

attemptAuthentication成功後,Authentication將設置爲SecurityContextHolder。然後你可以使用hasRole('xx'),或其他東西。