我无法理解为什么"授权:持票人__"没有使用Springfox 2.5.0在我的api中发送。我有以下配置:
private ApiKey apiKey() {
return new ApiKey(
"Authorization", // name: My key - Authorization
"api_key", // keyname: api_key
"header");
}
@Bean
SecurityConfiguration security() {
return new SecurityConfiguration(
null, null, null,
"Docserver2_fwk", // app name
"BEARER", // api key value
ApiKeyVehicle.HEADER, "Authorization", ",");
}
似乎我无法发送"授权:Bearer Token"在springfox(2.5.0)中,这可能吗?,这是一个已知的问题吗?
类似问题:https://github.com/springfox/springfox/issues/1812
PS:OpenAPI 3.0允许"承载"格式,例如:https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#jwt-bearer-sample
感谢。
答案 0 :(得分:9)
我正在使用2.8.0
版本,以下swagger配置适用于我。我在评论中提到,对于版本2.7.0
,一切都正常,但我升级到2.8.0
并且jwt令牌停止在请求标头中发送。我在Spring Boot版本 - 1.5.2.RELEASE
。
请注意,我想要一个用户可以手动输入JWT令牌的用户界面格式 - 承载... ,令牌应该放在Authorization
请求标头中。它不会自动与OAuth服务器集成。
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import com.google.common.base.Predicates;
import com.google.common.collect.Lists;
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
@SuppressWarnings("unchecked")
@Bean
public Docket swaggerPlugin() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.paths(PathSelectors.any())
.apis(Predicates.or(RequestHandlerSelectors
.basePackage("**controller package 1**"),
RequestHandlerSelectors
.basePackage("**controller package 2**")))
.build().directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.apiInfo(apiInfo())
.securitySchemes(Lists.newArrayList(apiKey()))
.securityContexts(Arrays.asList(securityContext()));
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("**Comment**")
.description("**Comment**")
.termsOfServiceUrl("**Comment**")
.contact("**Comment**")
.license("Apache License Version 2.0")
.licenseUrl("**Comment**").version("0.0.1")
.build();
}
@Bean
public SecurityConfiguration security() {
return SecurityConfigurationBuilder.builder().scopeSeparator(",")
.additionalQueryStringParams(null)
.useBasicAuthenticationWithAccessCodeGrant(false).build();
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations(
"classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
}
private ApiKey apiKey() {
return new ApiKey("apiKey", "Authorization", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth())
.forPaths(PathSelectors.any()).build();
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope(
"global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Arrays.asList(new SecurityReference("apiKey",
authorizationScopes));
}
}
答案 1 :(得分:5)
一种简单的解决方法是键入Bearer
而不是将令牌粘贴到令牌之后。您最终将看到一个文本框,其中包含:
Bearer <token>
我希望有一种更自动化的方法。但是现在看来,简单获取的文本框中的内容似乎已粘贴到给定标题条目的value部分中。我想之所以不会自动注入前缀Bearer
是因为Swagger会对用户使用哪种身份验证颇有意见!
@Configuration
@EnableSwagger2
class SwaggerConfig {
@Bean
Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build()
.securitySchemes(securitySchemes())
}
private static ArrayList<? extends SecurityScheme> securitySchemes() {
return [new ApiKey("Bearer", "Authorization", "header")]
}
}
REST端点方法:
@GetMapping("/count")
@ApiOperation(value = "Count the number of entities associated with resource name. This operation does not requires any role." , authorizations = [@Authorization(value = "Bearer")])
def count() {
count(service)
}
登录之前的curl
命令:
curl -X GET "http://localhost:8080/category/count" -H "accept: */*"
响应:
{
"timestamp": "2018-10-29T15:13:02.388+0000",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/category/count"
}
登录后的curl
命令:
curl -X GET "http://localhost:8080/category/count" -H "accept: */*" -H "Authorization: Bearer eyJhbGciOiJIUzUxMiJ9..."
响应:
{
"message": "There are 0 entities",
"count": 0
}
注意:我的代码在Groovy中,如果您使用的是标准Java,我确定您可以翻译。
答案 2 :(得分:1)
在swaggerversión2.9.2中对我有用的解决方案如下:
package com.example.springsocial;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import com.google.common.base.Predicates;
import com.google.common.collect.Lists;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.ignoredParameterTypes(AuthenticationPrincipal.class)
.select()
.apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
.paths(PathSelectors.any()).build()
.securitySchemes(Lists.newArrayList(apiKey()))
.securityContexts(Arrays.asList(securityContext()));
}
private ApiKey apiKey() {
return new ApiKey("apiKey", "Authorization", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth())
.forPaths(PathSelectors.any()).build();
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope(
"global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Arrays.asList(new SecurityReference("apiKey",
authorizationScopes));
}
}
POM.XML
<!-- SWAGGER -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<version>2.9.2</version>
</dependency>
SecurityConfig.JAVA
package com.example.springsocial.config;
import com.example.springsocial.security.*;
import com.example.springsocial.security.oauth2.CustomOAuth2UserService;
import com.example.springsocial.security.oauth2.HttpCookieOAuth2AuthorizationRequestRepository;
import com.example.springsocial.security.oauth2.OAuth2AuthenticationFailureHandler;
import com.example.springsocial.security.oauth2.OAuth2AuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Autowired
private CustomOAuth2UserService customOAuth2UserService;
@Autowired
private OAuth2AuthenticationSuccessHandler oAuth2AuthenticationSuccessHandler;
@Autowired
private OAuth2AuthenticationFailureHandler oAuth2AuthenticationFailureHandler;
@Autowired
private HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository;
@Bean
public TokenAuthenticationFilter tokenAuthenticationFilter() {
return new TokenAuthenticationFilter();
}
/*
By default, Spring OAuth2 uses HttpSessionOAuth2AuthorizationRequestRepository to save
the authorization request. But, since our service is stateless, we can't save it in
the session. We'll save the request in a Base64 encoded cookie instead.
*/
@Bean
public HttpCookieOAuth2AuthorizationRequestRepository cookieAuthorizationRequestRepository() {
return new HttpCookieOAuth2AuthorizationRequestRepository();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf()
.disable()
.formLogin()
.disable()
.httpBasic()
.disable()
.exceptionHandling()
.authenticationEntryPoint(new RestAuthenticationEntryPoint())
.and()
.authorizeRequests()
.antMatchers("/",
"/error",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js",
// swagger
"/swagger-ui.html**", "/swagger-resources/**",
"/v2/api-docs**", "/webjars/**"
)
.permitAll()
.antMatchers("/auth/**", "/oauth2/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.authorizationEndpoint()
.baseUri("/oauth2/authorize")
.authorizationRequestRepository(cookieAuthorizationRequestRepository())
.and()
.redirectionEndpoint()
.baseUri("/oauth2/callback/*")
.and()
.userInfoEndpoint()
.userService(customOAuth2UserService)
.and()
.successHandler(oAuth2AuthenticationSuccessHandler)
.failureHandler(oAuth2AuthenticationFailureHandler);
// Add our custom Token based authentication filter
http.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/common/**", "/v2/api-docs", "/configuration/ui", "/swagger-resources",
"/configuration/security", "/swagger-ui.html", "/webjars/**");
}
}
答案 3 :(得分:1)
我正在使用最新版本的springfox(现在是3.0.0),并且您可以将特定的承载auth与HttpAuthenticationScheme一起使用,而不是ApiKey:
ftp
答案 4 :(得分:0)
我将springfox-swagger2版本2.9.2与以下配置一起使用,并且可以通过swagger-ui传递JWT令牌。
private ApiKey apiKey() {
return new ApiKey("apiKey", Authorization, "header");
}
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.mycompany.dept.controller"))
.paths(PathSelectors.any())
.build().apiInfo(metaData()).securitySchemes(Lists.newArrayList(apiKey()));
}
在控制器中,我们需要使用@ApiOperation(值=“通过ID获取虚拟对象。”,授权= {@Authorization(value =“ apiKey”)} )
答案 5 :(得分:0)
下面的解决方案在2.8.0
版本中对我有用。
在Docket配置中添加以下代码
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.securitySchemes(Collections.singletonList(new ApiKey("JWT", "Authorization", "header")))
.securityContexts(Collections.singletonList(
SecurityContext.builder()
.securityReferences(
Collections.singletonList(SecurityReference.builder()
.reference("JWT")
.scopes(new AuthorizationScope[0])
.build()
)
)
.build())
)
.select()
.apis(RequestHandlerSelectors
.basePackage("com.test.controller"))
.paths(PathSelectors.regex("/.*"))
.build().apiInfo(apiEndPointsInfo());
}
在庄重的用户界面中单击Authorize
按钮后,在文本框中键入Bearer "XXXXXXXX(Token)"
答案 6 :(得分:0)
Jorge Santos Neill提供的解决方案为我工作。
唯一的变化是我的SecurityConfig.java,如下所述
I=J-1
答案 7 :(得分:0)
自 Springfox 3.0.0
起,此类授权有专用的 HttpAuthenticationScheme
配置。
JWT 授权配置示例:
@Bean
public Docket jwtSecuredDocket() {
HttpAuthenticationScheme authenticationScheme = HttpAuthenticationScheme
.JWT_BEARER_BUILDER
.name("JWT Token")
.build();
return new Docket(DocumentationType.OAS_30)
// <...>
.securitySchemes(Collections.singletonList(authenticationScheme));
}
这是一个更方便的解决方案,因为您不必每次都在 Swagger UI 的 Auth 模式中放置“Bearer”关键字 - 新机制会为您填充(这是以前解决方案的一个缺点)。
根据 commit introducing this feature 的消息,必须将摘要的 DocumentationType
设置为 OAS_30
才能使其正常工作。
答案 8 :(得分:0)
springfox 3.0.0 的另一个工作解决方案。
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.HttpAuthenticationScheme;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Autowired
private ServletContext context;
@Bean
public Docket api() {
HttpAuthenticationScheme authenticationScheme = HttpAuthenticationScheme.JWT_BEARER_BUILDER
.name("Authorization")
.build();
return new Docket(DocumentationType.OAS_30)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.ant(context.getContextPath() + "/api/**"))
.build()
.securityContexts(Arrays.asList(securityContext()))
.securitySchemes(Collections.singletonList(authenticationScheme));
}
private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth()).build();
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Arrays.asList(new SecurityReference("Authorization", authorizationScopes));
}
}