Spring Security JWT过滤器适用于所有请求 [英] Spring Security JWT Filter applies on all requests

查看:896
本文介绍了Spring Security JWT过滤器适用于所有请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Boot服务,该服务正在请求标头中接收在另一个服务中生成的JWT令牌. 我的目标是验证我的Spring Boot应用程序中JWT令牌的有效性.

I am working on a Spring Boot Service, which is receiving JWT Token generated in another service in the request header. My goal is to verify the validity of the JWT Token in my Spring Boot Application.

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

After researching a while I've decided to use WebSecurityConfig from Spring Security and to have some kind of a middleware which is actually a filter.

我已将过滤器配置为不应用于我的应用程序中定义的所有请求.但是无论如何,该筛选器都会应用于配置为allowAll()的请求.

I have configured the filter to be applied not on all request that are defined in my application. But regardless of this the filter is applied on requests that are configured as permitAll().

我对这一切完全感到困惑,无法弄清我的缺失.最后,我决定寻求帮助.请帮忙.

I am totally confused by this all and can't figure out what I am missing. Finally I have decided to ask for help. Please help.

这是我的代码.

安全配置:

@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

You need to use the ResourceServiceConfiguration class instead of WebSecurityConfig for JWT validation. Please check this link - 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");
    }

}

这篇关于Spring Security JWT过滤器适用于所有请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆