繁体   English   中英

Spring Security-如何在CustomTokenAuthenticationFilter中指定过滤器处理url

[英]Spring Security- How to specify filter processing url in CustomTokenAuthenticationFilter

我正在尝试使用令牌保护我的 Spring Rest API,这是我的自定义过滤器

public class CustomTokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private static final Logger logger = LoggerFactory.getLogger(CustomTokenAuthenticationFilter.class);

    public CustomTokenAuthenticationFilter(String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
        super.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(defaultFilterProcessesUrl));
        setAuthenticationManager(new NoOpAuthenticationManager());
        setAuthenticationSuccessHandler(new TokenSimpleUrlAuthenticationSuccessHandler());
    }


    public final String HEADER_SECURITY_TOKEN = "X-CustomToken"; 

    @Override 
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String token = request.getHeader(HEADER_SECURITY_TOKEN);
        logger.info("token found:"+token);
        AbstractAuthenticationToken userAuthenticationToken = authUserByToken(token);
        if(userAuthenticationToken == null || userAuthenticationToken.getPrincipal().equals("guest")) throw new AuthenticationServiceException(MessageFormat.format("Error | {0}", "Bad Token"));
        return userAuthenticationToken;
    }


    /**
     * authenticate the user based on token
     * @return
     */
    private AbstractAuthenticationToken authUserByToken(String token) {
        if(token==null) {
            return null;
        }
        AbstractAuthenticationToken authToken = new MyToken(token);
        try {
            return authToken;
        } catch (Exception e) {
            logger.error("Authenticate user by token error: ", e);
        }
        return authToken;
    }


    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        super.doFilter(req, res, chain);
    }

}

这是我配置它的方式

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    protected AbstractAuthenticationProcessingFilter getFilter() {
        return new CustomTokenAuthenticationFilter("/api/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.addFilterBefore(getFilter(), UsernamePasswordAuthenticationFilter.class)
        .csrf().disable();
    }
}

如果你看一下getFilter(),我已经通过了“/api/*”作为过滤器处理url,但是我想用HttpSecurity对象配置这些url,一些如下

http.authorizeRequests().antMatchers("/", "/rome").permitAll()
            .antMatchers("/api/admin", "/api/newUser").access("hasRole('ADMIN')")
            .antMatchers("/api/db").access("hasRole('ADMIN') or hasRole('DBA')")

我看到的问题是,自定义过滤器需要一个字符串作为“过滤器处理 url”,但我不想指定任何内容。 该信息应该通过antMatchers等配置HttpSecurity对象来antMatchers

真的有可能吗? 如果是,我怎么能做到这一点?

我使用了OncePerRequestFilter

public class MyAuthenticationFilter extends OncePerRequestFilter {

    // private RequestMatcher requestMatcher;
    private List<RequestMatcher> includedPathMatchers = new ArrayList<>();
    private List<RequestMatcher> excludedPathMatchers = new ArrayList<>();

    // implement getters and setters
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // your filter implementation and security logics
    }

}

您可以将此类视为普通 bean(使用@Autowired等)。 然后你只需要在你的上下文中注册它并将它注入到安全链中。

希望能帮助到你。

这个答案对你有用。 它说要使用 AbstractAuthenticationProcessingFilter 中可用的 setter setFilterProcessingURL()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM