【问题标题】:Spring security authentication filter url ignoredSpring 安全认证过滤器 url 被忽略
【发布时间】:2016-11-05 06:00:45
【问题描述】:

我想要完成的是我的 rest api 的基于 jwt 令牌的身份验证。 /api 下的所有内容都只能通过令牌访问。

我的网络安全配置中有以下配置方法:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authenticationProvider(authenticationProvider())
        .csrf().disable()
        .authorizeRequests().antMatchers("/api/**").authenticated()
    .and()
        .exceptionHandling()
        .authenticationEntryPoint(authenticationEntryPoint())
    .and()
        .addFilterBefore(authenticationFilter(),BasicAuthenticationFilter.class)
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

这是过滤器:

public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

public JwtAuthenticationFilter(AuthenticationManager manager) {
    super("/api/**");
    this.setAuthenticationManager(manager);
}

@Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
    return true;
}

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

    String header = request.getHeader("Authorization");

    if (header == null || !header.startsWith("Bearer ")) {
        throw new JwtTokenMissingException("No JWT token found in request headers");
    }

    String authToken = header.substring(7);

    JwtAuthenticationToken authRequest = new JwtAuthenticationToken(authToken);

    return getAuthenticationManager().authenticate(authRequest);
}

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult)
        throws IOException, ServletException {
    super.successfulAuthentication(request, response, chain, authResult);
    chain.doFilter(request, response);
}
}

我的问题是过滤器现在应用于每个 url,而不仅仅是带有 /api 前缀的那些。

我知道我的“配置”方法可能是错误的,但它应该是什么样子?我想要完成的就是使用 /api 路径的过滤器。

+1 问题:为什么有两个值来配置将应用过滤器的路径? (曾经作为配置中 antMatchers 方法的参数,然后是 AbstractAuthenticationProcessingFilter 的构造函数参数“filterProcessesUrl”)。这些值如何相互关联,我应该使用哪一个?

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    问题出在这部分:

    @Override
    protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
        return true;
    }
    

    我复制了它,但从未意识到它在那里。

    【讨论】:

    • 我想如果你在.addFilterBefore之前添加.antMatcher("/api/**"),你的问题也将得到解决。
    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2015-09-06
    • 1970-01-01
    • 2018-12-09
    相关资源
    最近更新 更多