Spring 安全检查的标头存在一些固定值

use*_*466 2 java spring spring-security

假设我有 Spring Boot Rest 服务,我想用这个简单的逻辑来保护它,如果存在值为“123456”的标头“token”,那么请求就可以了,我应该处理它,如果没有,那么我应该发回未经授权的 401 http 错误。

我如何在 Spring Boot 1.5 中实现这个逻辑。

小智 6

通过实施一个GenericFilterBean.

public class CustomAuthenticationFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // get header and validate from request object
        filterChain.doFilter(request, response);
    }
}
Run Code Online (Sandbox Code Playgroud)

并将过滤器连接到您的安全配置中。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            // other security config
            .addFilterBefore(new CustomAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
Run Code Online (Sandbox Code Playgroud)