2017-02-21 108 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并验证它,并在出现问题时抛出错误。 –