java - Spring Security JWT 过滤器适用于所有请求

标签 java spring spring-boot spring-security jwt

我正在开发一个 Spring Boot 服务,该服务正在请求 header 中接收另一个服务中生成的 JWT token 。 我的目标是验证 Spring Boot 应用程序中 JWT token 的有效性。

经过一段时间的研究,我决定使用 Spring Security 的 WebSecurityConfig 并拥有某种实际上是过滤器的中间件。

我已将过滤器配置为不适用于我的应用程序中定义的所有请求。但无论如何,过滤器都会应用于配置为 PermitAll() 的请求。

我对这一切感到完全困惑,无法弄清楚我错过了什么。最后我决定寻求帮助。请帮忙。

这是我的代码。

安全配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
JWTAuthenticationFilter jwtAuthenticationFilter;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/req").permitAll()
            .and()
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        // And filter other requests to check the presence of JWT in header
        .addFilterBefore(jwtAuthenticationFilter,
                BasicAuthenticationFilter.class);
}

@Override
public void configure(WebSecurity webSecurity) {
    webSecurity
        .ignoring()
            .antMatchers("/req");
    }
}

过滤器:

@Component
public class JWTAuthenticationFilter extends GenericFilterBean {
@Autowired
TokenAuthenticationService tokenAuthenticationService = new TokenAuthenticationService();
@Override
public void doFilter(ServletRequest request,
        ServletResponse response,
        FilterChain filterChain)
                throws IOException, ServletException {
    boolean authentication = tokenAuthenticationService
            .getAuthentication((HttpServletRequest)request);

    if (!authentication) {
        ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    filterChain.doFilter(request,response);
    }
}

身份验证服务:

@Component
class TokenAuthenticationService {
@Value("${security.authentication.token.secret}")
private String SECRET;
@Value("${security.authentication.token.token_prefix}")
private String TOKEN_PREFIX;
@Value("${security.authentication.token.header_string}")
private String HEADER_STRING;

boolean getAuthentication(HttpServletRequest request) throws UnsupportedEncodingException {
    String token = request.getHeader(HEADER_STRING);

    if (token != null) {
        // parse the token.
        DecodedJWT jwt;
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                .build(); //Reusable verifier instance
            jwt = verifier.verify(token);

            return true;
        } catch (UnsupportedEncodingException exception){
            //UTF-8 encoding not supported
            UnsupportedEncodingException ex = exception;
            return false;
        } catch (JWTVerificationException exception){
            //Invalid signature/claims
            JWTVerificationException ex = exception;
            return false;
        }
    }
    return false;
    }
}

最佳答案

您需要使用 ResourceServiceConfiguration 类而不是 WebSecurityConfig 来进行 JWT 验证。请检查此链接 - https://github.com/manishsingh27/TokenBasedAuth/tree/main/stdedu/src/main/java/com/adms/stdedu/config

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

@Configuration
//@Order(-21)
@EnableResourceServer
public class ResourceServiceConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/**").hasAnyAuthority ("READ_PRIVILEGE","WRITE_PRIVILEGE");
    }

}

关于java - Spring Security JWT 过滤器适用于所有请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46548426/

相关文章:

java - Eclipse:如何将Web项目转换为AspectJ项目并使用AJDT插件编织运行?

java - MultiActionController 的替换类,在 4.3.3 中已弃用

ios - 如何通过 Java(Spring Boot) 使用 FCM 向 iOS 设备发送通知/消息?

Java 嵌套类实例防止外部类GC

具有 HTML5 boolean 属性的 Java Spring 表单字段

spring-boot - 其他程序语言客户端如何使用Spring Cloud Config Server?

spring-boot - 将springboot输出保存到elasticsearch引擎

java - 在进行批量更新时,PostUpdate Hook 不起作用

java - 正则表达式:找到 "bar"但找不到 "foo bar"

java - 如何将java列表对象的特定字段转换为jsonarray