• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

用户头像
it1352
帮助1

问题说明

我正在使用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;
    }
}

正确答案

#1

您需要使用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");
    }

}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfhiki
系列文章
更多 icon
同类精品
更多 icon
继续加载