Spring 安全性 - 允许所有内容不起作用

问题描述 投票:0回答:1

我尝试排除

/actuator
端点进行身份验证。

我有以下配置:

    @Bean
    public SecurityFilterChain securityWebFilterChain(
            HttpSecurity http,
            JwtTokenProvider jwtTokenProvider) throws Exception {

        return http
                .csrf(AbstractHttpConfigurer::disable)
                .httpBasic(AbstractHttpConfigurer::disable)
                .sessionManagement(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(
                        authz -> authz
                                .requestMatchers("/actuator/**").permitAll()
                                .requestMatchers("/api/**").hasRole("USER")
                                .anyRequest().authenticated())
                .addFilterAt(new JwtTokenAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class)
                .build();
    }

但是,拨打

/actuator/info
需要授权。

当我像这样注册

WebSecurityCustomizer
时,就可以了。

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring().requestMatchers("/actuator/**");
}

但我收到以下警告消息:

You are asking Spring Security to ignore Mvc [pattern='/actuator/**'].  
This is not recommended -- please use permitAll via HttpSecurity#authorizeHttpRequests instead.

我的

application.yml
配置:

management:
  endpoints:
    web:
      exposure:
        include: info, health, prometheus

调试输出:

2024-04-23T10:04:56.267+02:00  INFO 69256 --- [nio-8080-exec-4] Spring Security Debugger                 : 

************************************************************

Request received for GET '/actuator/info':

org.apache.catalina.connector.RequestFacade@13de2731

servletPath:/actuator/info
pathInfo:null
headers: 
host: localhost:8080
connection: keep-alive
cache-control: max-age=0
sec-ch-ua: "Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
sec-fetch-site: none
sec-fetch-mode: navigate
sec-fetch-user: ?1
sec-fetch-dest: document
accept-encoding: gzip, deflate, br, zstd
accept-language: en-US,en;q=0.9,pl;q=0.8
cookie: Idea-9db45725=ebc97136-1c3f-4057-a7c2-e1254e0cf200; JSESSIONID=DCD0D8B5278250DF2A0329311A9D5103


Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextHolderFilter
  HeaderWriterFilter
  CorsFilter
  LogoutFilter
  JwtTokenAuthenticationFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  ExceptionTranslationFilter
  AuthorizationFilter
]


************************************************************



2024-04-23T10:04:56.268+02:00 ERROR 69256 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception

java.lang.RuntimeException: Invalid token
    at com.my.JwtTokenAuthenticationFilter.doFilterInternal(JwtTokenAuthenticationFilter.java:41) ~[main/:na]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.6.jar:6.1.6]

如何配置

/actuator/**
以推荐的方式被忽略?

spring spring-security
1个回答
0
投票

问题出在过滤器上。所有请求都通过此过滤器,如果需要,应添加授权。

所以代替:

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {

        String token = resolveToken(request);
        if (token != null && validateToken(token)) {
            Authentication authentication = getAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            doFilter(request, response, filterChain);
        }else {
            throw new RuntimeException("Invalid token");
        }
    }

我将其重构为:

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {

        String token = resolveToken(request);
        if (token != null && validateToken(token)) {
            Authentication authentication = getAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
        }

        doFilter(request, response, filterChain);
    }

请记住,在生产就绪的项目中,您应该使用以下内容:https://docs.spring.io/spring-security/reference/reactive/oauth2/resource-server/jwt.html

© www.soinside.com 2019 - 2024. All rights reserved.