gpt4 book ai didi

java - 使用 JWT 配置 swagger

转载 作者:行者123 更新时间:2023-12-04 03:00:02 25 4
gpt4 key购买 nike

我想为我的 SpringBoot 应用程序安装 SWAGER。似乎 JWT 不提供对 swagger URL 的访问权限。

我正在尝试通过 url localhost:8088/swagger-ui.html 访问它

这是 SwaggerConfig 类

@EnableSwagger2
@Configuration
public class SwaggerConfig {


@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("Path.to.my.controller"))

.build();

}


}

我还尝试从 link 添加 WebAppConfig与下一个内容

@Configuration
@EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}

}

并尝试设置忽略 url:

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}

}

此版本的代码提供了从 swagger url 到“localhost:8088/login”的自动重定向。但是下一个返回的只是空页面

已更新

  web.ignoring().antMatchers("/", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**");

gaps中的url是我调试issuse时看到的url。这个 url 被 swagger 调用。

更新部分结束

主类

 @SpringBootApplication
public class Application extends SpringBootServletInitializer {

public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));
SpringApplication app = new SpringApplication(Application.class);
app.run();
}

@Bean
@Autowired
public FilterRegistrationBean jwtFilterRegistration(JwtUtil jwtUtil, UserService userService) {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new JwtFilter(jwtUtil, userService));

filterRegistrationBean.addUrlPatterns("/*");

// ordering in the filter chain
filterRegistrationBean.setOrder(1);
return filterRegistrationBean;
}

// Request Interceptor for checking permission with custom annotation.
@Bean
public MappedInterceptor PermissionHandlerInterceptor() {
return new MappedInterceptor(null, new PermissionHandlerInterceptor());
}

Pom xml 包含所有需要的依赖项。当我在主类 jwt 方法中发表评论时,我可以访问 swagger。所以我在 JWT 中得出了这个问题的结论。如果需要一些额外的信息,我会添加。

已更新

起初 swagger-url 给白标页面错误“Unathorized”在对代码进行一些操作后,它给出了空白页面。

最佳答案

我最近不得不做同样的事情。您需要告诉 Spring Security 允许所有 Swagger 资源。试试这个:

 @Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// we don't need CSRF because our token is invulnerable
.csrf().disable()


.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

// don't create session

.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()

.authorizeRequests()

// allow anonymous resource requests
.antMatchers(
HttpMethod.GET,
"/",
"/v2/api-docs", // swagger
"/webjars/**", // swagger-ui webjars
"/swagger-resources/**", // swagger-ui resources
"/configuration/**", // swagger configuration
"/*.html",
"/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.js"
).permitAll()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated();

// Custom JWT based security filter
httpSecurity
.addFilterBefore(authenticationTokenFilter,
UsernamePasswordAuthenticationFilter.class);

// disable page caching
httpSecurity.headers().cacheControl();
}

这是我的 Swagger 摘要配置。如果您想将 token 应用到所有端点,它还包括授权 header 。

@Bean
public Docket newsApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.securitySchemes(Lists.newArrayList(apiKey()))
.securityContexts(Lists.newArrayList(securityContext()))
.apiInfo(generateApiInfo());
}

@Bean
SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.any())
.build();
}

List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope
= new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Lists.newArrayList(
new SecurityReference("JWT", authorizationScopes));
}

private ApiKey apiKey() {
return new ApiKey("JWT", "Authorization", "header");
}

关于java - 使用 JWT 配置 swagger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50061314/

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