创建自定义注释以从标头验证userToken

时间:2017-02-21 08:01:30

标签: java spring spring-aop spring-annotations

我正在尝试使用自定义注释创建一个独立的可打包jar,它包含在控制器映射函数中(并将userToken作为标头中的输入),返回一个布尔值,无论用户是经过身份验证还是现在。

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

我知道这不是正确的语法,因为使用此代码会产生错误,即RequestMapping无法转换为String(并且注释只接受原始值)。

我也对其他方法持开放态度,但它应该只有在需要时才能灵活地返回认证布尔值,而不是通过全局拦截。

重要:请注意@Authenticator来自一个独立的软件包,通过Maven在当前软件包中导入。 HTTPServletRequest是否会传递ConstraintValidator。

1 个答案:

答案 0 :(得分:0)

使用spring security 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();
    }
相关问题