You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot配置Swagger后访问提示Unauthorized认证错误排查

问题

在Spring Boot后端配置Swagger后,已在WebSecurityConfig的configure方法中放行Swagger相关路径,但访问地址http://localhost:8080/spring-security-rest/api/v2/api-docs时仍返回“Full authentication is required to access this resource”未授权错误,日志显示系统会保护Mvc路径/v2/api-docs。

相关配置代码

WebSecurityConfig的configure方法

protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests().antMatchers("/api/account/**").permitAll()
                .antMatchers("/api/station/**").permitAll()
                .antMatchers("/api/contact/**").permitAll()
                .antMatchers("/api/package/**").permitAll()
                .antMatchers("/api/location/**").permitAll()
                .antMatchers("/api/borders-filter/**").permitAll()
                .antMatchers("/api/weather/**").permitAll()
                .antMatchers("/api/promo/**").permitAll()
                .antMatchers("/api/activity/**").permitAll()
                .antMatchers("/api/shop/get-card-price-by-station").permitAll()
                .antMatchers("/api/partner/time-slot/get-slots-between-dates-by-activities").permitAll()
                .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**","/swagger-resources/configuration/ui","/swagger-ui.html").permitAll()
                .anyRequest().authenticated();

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }

AuthEntryPointJwt类

public class AuthEntryPointJwt implements AuthenticationEntryPoint {

    private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        logger.error("Unauthorized error: {}", authException.getMessage());
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error: Unauthorized");
    }

}

日志信息

2022-10-13 09:59:03.379  INFO 4108 --- [           main] fr.veryski.veryski.VeryskiApplication    : Starting VeryskiApplication using Java 16.0.2 on fnyve with PID 4108 (C:\Users\qwert\OneDrive\BUREAU\Veryski\veryski\target\classes started by qwert in C:\Users\qwert\OneDrive\BUREAU\Veryski\veryski)
2022-10-13 09:59:03.381  INFO 4108 --- [           main] fr.veryski.veryski.VeryskiApplication    : The following profiles are active: dev
2022-10-13 09:59:05.199  INFO 4108 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler@27bcb4ad' of type [org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-10-13 09:59:05.206  INFO 4108 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'methodSecurityMetadataSource' of type [org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-10-13 09:59:05.464  INFO 4108 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-10-13 09:59:05.473  INFO 4108 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-10-13 09:59:05.473  INFO 4108 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.44]
2022-10-13 09:59:05.601  INFO 4108 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-10-13 09:59:05.601  INFO 4108 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2165 ms
2022-10-13 09:59:05.786  INFO 4108 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-10-13 09:59:05.887  INFO 4108 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2022-10-13 09:59:08.702  INFO 4108 --- [           main] l.lockservice.StandardLockService        : Successfully acquired change log lock
2022-10-13 09:59:09.074  INFO 4108 --- [           main] l.c.StandardChangeLogHistoryService      : Reading from public.databasechangelog
2022-10-13 09:59:09.136  INFO 4108 --- [           main] l.lockservice.StandardLockService        : Successfully released change log lock
2022-10-13 09:59:10.795  INFO 4108 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure Mvc [pattern='/v2/api-docs'] with []
2022-10-13 09:59:10.795  INFO 4108 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure Mvc [pattern='/configuration/ui'] with []
2022-10-13 09:59:10.795  INFO 4108 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure Mvc [pattern='/swagger-resources/**'] with []
2022-10-13 09:59:10.795  INFO 4108 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure Mvc [pattern='/configuration/security'] with []
2022-10-13 09:59:10.795  INFO 4108 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure Mvc [pattern='/swagger-ui.html'] with []
2022-10-13 09:59:10.795  INFO 4108 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure Mvc [pattern='/webjars/**'] with []
2022-10-13 09:59:10.824  INFO 4108 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@2cf5cc43, org.springframework.security.web.context.SecurityContextPersistenceFilter@6639a9f0, org.springframework.security.web.header.HeaderWriterFilter@28ec9c23, org.springframework.web.filter.CorsFilter@52a3a9ef, org.springframework.security.web.authentication.logout.LogoutFilter@60d46bd7, fr.veryski.veryski.config.AuthTokenFilter@26107e6d, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@51430893, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@2e37cd0, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@25d77b18, org.springframework.security.web.session.SessionManagementFilter@29ad358c, org.springframework.security.web.access.ExceptionTranslationFilter@2b515b5c, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@33588b68]
2022-10-13 09:59:10.931  INFO 4108 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2022-10-13 09:59:11.134  INFO 4108 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'taskScheduler'
2022-10-13 09:59:11.240  INFO 4108 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-10-13 09:59:12.061  INFO 4108 --- [           main] fr.veryski.veryski.VeryskiApplication    : Started VeryskiApplication in 9.455 seconds (JVM running for 10.485)
2022-10-13 10:00:49.961  INFO 4108 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-10-13 10:00:49.962  INFO 4108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-10-13 10:00:49.966  INFO 4108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 4 ms
2022-10-13 10:00:50.019 ERROR 4108 --- [nio-8080-exec-1] f.v.veryski.config.AuthEntryPointJwt     : Unauthorized error: Full authentication is required to access this resource
2022-10-13 10:00:50.339 ERROR 4108 --- [nio-8080-exec-2] f.v.veryski.config.AuthEntryPointJwt     : Unauthorized error: Full authentication is required to access this resource

问题分析与解决方案

问题根源

你访问的Swagger路径实际被Spring Security匹配的是/api/v2/api-docs,但配置中antMatchers放行的是/v2/api-docs,缺少了/api前缀,导致该请求路径未被纳入放行规则,被认证拦截器拦截。日志中Will secure Mvc [pattern='/v2/api-docs']也说明Spring Security保护的是无/api前缀的路径,和你的请求路径不匹配。

解决方案

修改WebSecurityConfig中Swagger相关路径的antMatchers,给所有Swagger路径加上/api前缀,确保和实际请求路径匹配:

.antMatchers("/api/v2/api-docs", "/api/configuration/ui", "/api/swagger-resources/**", "/api/configuration/security", "/api/swagger-ui.html", "/api/webjars/**","/api/swagger-resources/configuration/ui").permitAll()

修改后重启应用,访问原地址即可正常获取Swagger文档,无需认证。

内容的提问来源于stack exchange,提问作者l3miage-crivoid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:10:53