Swagger:授权令牌未传递到请求标头中

问题描述 投票:2回答:2

我使用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) {
...
}

拨打此电话,用户需要授权令牌授权:Bearer {token}

女巫来自身份验证服务器。我试图用招摇方式首次呼叫此服务器,并将其传递给控制器​​请求,如上述请求。所以我做

@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");
    }

效果很好。任何想法为什么会这样?

oauth-2.0 swagger springfox
2个回答
0
投票

为什么您希望令牌自动添加到标题?调用auth端点以接收令牌时,始终必须自己(手动或以编程方式)将该令牌放入后续请求标头中。令牌管理始终从客户端进行,服务器仅将令牌提供给经过身份验证的代理,并检查其有效性。它永远不要自动将它们添加到标头中,因为这会破坏令牌的目的。


0
投票

据我所知,Swagger仅在配置令牌时才使用令牌,并且使用Swagger UI页面右上角的“授权”按钮进行配置。

所以,理想的情况是:

  1. 返回令牌的触发器Auth调用

  2. 复制令牌;单击“授权”按钮,然后将JWT令牌粘贴到“承载者”

此后,所有后续调用都应使用此令牌,直到您按注销为止。

© www.soinside.com 2019 - 2024. All rights reserved.