2017-02-21 41 views
3

我想創建一個獨立的可打包的jar與自定義註釋,它包含在一個控制器映射函數(並採取userToken作爲輸入的頭),返回一個布爾值是否用戶經過身份驗證或現在。創建一個自定義註釋來驗證標頭userToken

// Expected way of inclusion 
public @ResponseBody boolean isAuthenticated(@Authenticator(@RequestHeader("userToken")) Boolean isUserAuthenticated) { 
return isUserAuthenticated; 
} 

我知道這不會是正確的語法,因爲使用此代碼給出了錯誤RequestMapping不能轉換成字符串(和註解只接受原始值)。

我也對其他方法開放,但它應該具有靈活性來僅在需要時返回認證布爾值,而不是通過全局攔截。

重要:請注意@Authenticator來自一個獨立的包裝,通過Maven的進口在當前包。 HTTPServletRequest是否會在ConstraintValidator中傳遞。

+1

我想你,你想改寫春季安全。 –

+0

請在此處提及哪些Spring安全模塊可以重複使用。另外,我想要一個簡單的包,所以我沒有包含太多的依賴關係。 –

+0

我已經添加了答案。 –

回答

0

使用Spring安全BasicAuthenticationFilter一樣:

public class MyBasicAuthenticationFilter extends BasicAuthenticationFilter { 

    private AuthenticationManager authenticationManager; 

    public MyBasicAuthenticationFilter(AuthenticationManager authenticationManager) { 
     super(authenticationManager); 
     this.authenticationManager=authenticationManager; 
    } 

    @Override 
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { 
     // do you checks here 
     super.doFilterInternal(request, response, chain); 
    } 
} 

然後添加到您的安全配置的東西,如:

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
       .authorizeRequests() 
       .antMatchers("/", "/home").permitAll() 
       .anyRequest().authenticated() 
       .and() 
       .formLogin() 
       .loginPage("/login") 
       .permitAll() 
       .and() 
       .logout() 
       .permitAll(); 

     http.addFilterBefore(new MyBasicAuthenticationFilter(authenticationManager()); 
    } 

    @Bean 
    public AuthenticationManager authenticationManager() { 
     return new MyAuthenticationManager(); 
    } 
+0

感謝您的幫助,但這是我需要的。請注意,我的軟件包將包含在其他項目中,註釋應該只接受userToken並驗證它,並在出現問題時拋出錯誤。 –