我使用springfox 2.9.2 我有类似的api:
@Api(tags = "Users")
@RestController
@RequestMapping("users")
public class UsersController {
@ApiOperation(value = "Creates a user")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "user created"),
@ApiResponse(code = 401, message = "not authorized")})
@PostMapping(value = "/add")
public ResponseEntity addUser(@Valid @RequestBody UserDTO userDTO) {
...
}
要进行此呼叫,用户需要授权令牌 授权:不记名{token}
witch来自身份验证服务器。 我试图用招摇方式首次呼叫此服务器,并将其传递给控制器请求,如上述请求。 所以我
@Bean
public Docket api() {
final String swaggerToken = "";
return new Docket(DocumentationType.SWAGGER_2)
@Bean
public .select()
.apis(RequestHandlerSelectors.basePackage("com.mbv.coros.notification.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiEndPointsInfo())
.securitySchemes(Arrays.asList(securityScheme()))
.securityContexts(Arrays.asList(securityContext()))
.useDefaultResponseMessages(false);
}
private SecurityScheme securityScheme() {
GrantType grantType = new ResourceOwnerPasswordCredentialsGrant(AUTH_SERVER + "/token");
SecurityScheme oauth = new OAuthBuilder().name("spring_oauth")
.grantTypes(Arrays.asList(grantType))
.scopes(Arrays.asList(scopes()))
.build();
return oauth;
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.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));
}
Swagger ui授权调用上的成功返回了令牌,但是没有将其添加到请求标头中。它会生成
curl -X GET "http://localhost:8080/users/get" -H "accept: */*"
如果我将令牌设置为:
.securitySchemes(Arrays.asList(apiKey()))
private ApiKey apiKey() {
return new ApiKey("JWT", AUTHORIZATION_HEADER, "header");
}
它运行完美。 任何想法为什么会这样?
答案 0 :(得分:0)
据我所知,Swagger仅在配置令牌时才使用令牌,并且使用Swagger UI页面右上方的“授权”按钮进行配置。
因此,理想的情况是:
触发Auth调用,返回令牌
复制令牌;单击“授权”按钮,然后将JWT令牌粘贴到“承载者”中
此后,所有后续调用都应使用此令牌,直到您按注销。