gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:05:08 25 4
gpt4 key购买 nike

我正在开发一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com