Swagger Ui shows Unauthorized message for Authorization in my Spring Boot

Viewed 637

I have a problem about showing user content through Swagger Ui version 2.9.2.

After I get token from signing-in process, I put it into the Authorized part as a JWT.

When I try to run /user request, I get an error shown below.

{
  "path": "/api/pages/user",
  "error": "Unauthorized",
  "message": "Full authentication is required to access this resource",
  "status": 401
}

How can I fix it?

Here is a function to show user content below.

@ApiOperation(value = "userAccess", authorizations = { @Authorization(value="JWT") })
@GetMapping("/user")
@PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
public String userAccess() {
   return "User Content.";
} 

Here is my Swagger Config shown below.

@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {

    public static final String AUTHORIZATION_HEADER = "Authorization";

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).select()
                .apis(RequestHandlerSelectors.basePackage("com.refreshtokenjwt.app"))
                .paths(PathSelectors.regex("/.*"))
                .build().apiInfo(apiEndPointsInfo())
                .securitySchemes(Arrays.asList(apiKey()))
                .securityContexts(Arrays.asList(securityContext()))
                ;

    }

    private ApiInfo apiEndPointsInfo() {
        return new ApiInfoBuilder().title("Title")
    }

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

    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 Arrays.asList(new SecurityReference("JWT", authorizationScopes));
    }

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

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}
0 Answers
Related