英文:
How do i whitelist api in JWT Filter
问题
我有一个名为SpringSecurityWebAppConfig
的类,它使用了我自己的过滤器类JwtAuthenticationFilter
。
现在的问题是,如何绕过我的JwtAuthenticationFilter
,以便针对没有请求头和/或令牌的 API 调用。我是否应将其设置为可配置项,并在过滤器中读取它?
我的JwtAuthenticationFilter
是从另一个库导入的类。其目的是为了在其他微服务中重用该文件。
示例:
/scanFile
不需要请求令牌。当我将其添加到 SpringSecurityWebAppConfig
中时,我的过滤器会抛出 401 错误,因为它没有请求令牌。
SpringSecurityWebAppConfig
类:
public class SpringSecurityWebAppConfig extends WebSecurityConfigurerAdapter {
@Autowired
public JwtAuthenticationFilter jwtAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/homePage").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
.antMatchers("/userPage").access("hasRole('ROLE_USER')")
.antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")
.antMatchers(HttpMethod.DELETE, "/data").access("hasRole('ROLE_ADMIN')")
.antMatchers("/login").permitAll()
.antMatchers("/logout").authenticated()
.and()
.anonymous().disable()
.exceptionHandling()
.authenticationEntryPoint(new CustomAuthenticationEntryPoint())
.and()
.headers()
.httpStrictTransportSecurity()
.includeSubDomains(true).maxAgeInSeconds(31536000);
// Add a filter to validate the tokens with every request
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
}
JwtAuthenticationFilter
类:
private void getJwtFromRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String bearerToken = request.getHeader("Authorization");
// Step 1: Check if bearer token exist in authorization header and if bearer token start with "Bearer "
if (!StringUtils.hasText(bearerToken) || !bearerToken.startsWith("Bearer ")) {
String errorMsg = "No access token found in request headers.";
Error err = new Error(JWT_AUTHENTICATION_FILTER, "AccessTokenMissingException", errorMsg);
// Java object to JSON string
String jsonString = mapper.writeValueAsString(err);
log.error(jsonString);
throw new AccessTokenMissingException(errorMsg);
}
//rest of the processing here ...
}
英文:
I have SpringSecurityWebAppConfig
class that uses my own filter class JwtAuthenticationFilter
.
The question now is how do i bypass my JwtAuthenticationFilter for api calls that does not have request header and/or token. Do I set it as a configurable and read it in the filter?
My JwtAuthenticationFilter
is an imported class from another library. The purpose is to reuse the file for the other microservices.
Example:
/scanFile
does not need request token. When I add into SpringSecurityWebAppConfig. My filter is throw 401 as it does not have request token.
SpringSecurityWebAppConfig class:
public class SpringSecurityWebAppConfig extends WebSecurityConfigurerAdapter {
@Autowired
public JwtAuthenticationFilter jwtAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/homePage").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
.antMatchers("/userPage").access("hasRole('ROLE_USER')")
.antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")
.antMatchers(HttpMethod.DELETE, "/data").access("hasRole('ROLE_ADMIN')")
.antMatchers("/login").permitAll()
.antMatchers("/logout").authenticated()
.and()
.anonymous().disable()
.exceptionHandling()
.authenticationEntryPoint(new CustomAuthenticationEntryPoint())
.and()
.headers()
.httpStrictTransportSecurity()
.includeSubDomains(true).maxAgeInSeconds(31536000);
// Add a filter to validate the tokens with every request
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
}
JwtAuthenticationFilter Class:
private void getJwtFromRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String bearerToken = request.getHeader("Authorization");
// Step 1: Check if bearer token exist in authorization header and if bearer token start with "Bearer "
if (!StringUtils.hasText(bearerToken) || !bearerToken.startsWith("Bearer ")) {
String errorMsg = "No access token found in request headers.";
Error err = new Error(JWT_AUTHENTICATION_FILTER, "AccessTokenMissingException", errorMsg);
// Java object to JSON string
String jsonString = mapper.writeValueAsString(err);
log.error(jsonString);
throw new AccessTokenMissingException(errorMsg);
}
//rest of the processing here ...
}
答案1
得分: 0
所以您想在没有Spring Security身份验证的情况下对某些API进行白名单处理?
您可以在SpringSecurityWebAppConfig中使用web.ignoring().antMatchers(),将这些URL从Spring Security中排除。
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/scanFile/**");
}
英文:
so you want to whitelist some apis even without spring security authentication?
you can use web.ignoring().antMatchers() in your SpringSecurityWebAppConfig, to exclude the urls from spring security.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/scanFile/**”);
}
专注分享java语言的经验与见解,让所有开发者获益!
评论