SpringBoot集成Swagger遇JWT权限问题:无法访问Swagger页面
Hey there, let's fix that Swagger access issue blocked by your JWT authentication setup! The root cause is your security rules are restricting access to all Swagger-related endpoints. Here's how to sort this out step by step:
1. Whitelist Swagger Endpoints in Your Security Setup
First, you need to let your security layer know that Swagger paths don't require JWT auth. The approach depends on how you've implemented JWT:
If using Spring Security
Update your SecurityConfig class to permit access to all Swagger-related endpoints:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() // Allow all Swagger-related paths .antMatchers( "/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs", "/webjars/**" ).permitAll() // Require auth for all other endpoints .anyRequest().authenticated() // Add your existing JWT filters here .and() .addFilter(new JwtAuthenticationFilter(authenticationManager())) .addFilter(new JwtAuthorizationFilter(authenticationManager())); } }
If using a custom JWT Interceptor (HandlerInterceptor)
If you have a custom interceptor for JWT validation, exclude Swagger paths in your WebAppConfig (or WebMvcConfigurer implementation):
@Configuration public class WebAppConfig implements WebMvcConfigurer { @Autowired private JwtInterceptor jwtInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(jwtInterceptor) .addPathPatterns("/**") // Apply to all paths... // ...except Swagger ones .excludePathPatterns( "/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs", "/webjars/**" ); } }
2. Update SwaggerConfig to Support JWT Authentication
Even if you can access the Swagger UI now, you'll need to let Swagger send JWT tokens when testing your endpoints. Enhance your SwaggerConfig like this:
@EnableSwagger2 @Configuration public class SwaggerConfig { @Bean public Docket productApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("Path.to.my.controller")) .paths(PathSelectors.any()) .build() // Add JWT auth support .securitySchemes(Collections.singletonList(apiKey())) .securityContexts(Collections.singletonList(securityContext())); } private ApiKey apiKey() { // Define the JWT token header return new ApiKey("JWT", "Authorization", "header"); } private SecurityContext securityContext() { // Apply auth to all endpoints return SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.any()) .build(); } private List<SecurityReference> defaultAuth() { AuthorizationScope scope = new AuthorizationScope("global", "access all endpoints"); return Collections.singletonList(new SecurityReference("JWT", new AuthorizationScope[]{scope})); } }
This adds an Authorize button at the top of your Swagger UI. Click it, enter Bearer <your-jwt-token> (make sure there's a space after "Bearer"), and all subsequent API calls will automatically include the JWT token in the request header.
3. Test It Out
- Restart your Spring Boot application
- Navigate to
localhost:8088/swagger-ui.html— it should load without issues now - Use the "Authorize" button to add your JWT token
- Test your endpoints through Swagger; they should pass JWT authentication successfully
内容的提问来源于stack exchange,提问作者artemk

