0

I am creating a Rest microservice with SpringBoot and Swagger (using springdoc-openapi-webmvc-core v1.6.5). To enable and configurate Swagger I created this class:


import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableAutoConfiguration
@EnableWebMvc
@OpenAPIDefinition(info = @Info(title = "User Management API", version = "1.0", description = "Documentation User Management API v1.0"))
@SecurityScheme(name = OpenApi30Config.SECURITY_SCHEME_NAME, scheme = "Bearer", type = SecuritySchemeType.HTTP, in = SecuritySchemeIn.HEADER )
public class OpenApi30Config {

    public static final String SECURITY_SCHEME_NAME = "Authorization";

}

One of the endpoints looks like this:


@RestController
@Validated
@RequestMapping(value = "/api/roles", name = "Role Controller")
@Tag(name = "Roles", description = "Controller to get the information of the HORUS role users.")
@CrossOrigin(origins = "*")
@SecurityRequirement(name = OpenApi30Config.SECURITY_SCHEME_NAME)
public class RoleController {

    @Operation(summary = "Returns all Role Users")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "All registered Roles Found", content = {@Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = RRole.class)))}),
            @ApiResponse(responseCode = "404", description = "No Users Found", content = {@Content()})
    })
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<List<RRole>> findAllRoles() {
...
    }
}

I Configurated my swagger to user JWT authentication which will be intercepted by a filter:

@Component
@Slf4j
public class AuthenticatedFilter extends OncePerRequestFilter {

   @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain)
            throws IOException {
        log.debug("FILTER: {}", request.getRequestURI());

        // LOG ALL HEADERS
        Collections
                .list(request.getHeaderNames())
                .forEach(headerNAme -> log.debug("FILTER {} : {}", headerNAme, request.getHeader(headerNAme)));
        final String requestTokenHeader = request.getHeader("Authorization");
        // I use this requestTokenHeader for authentication
        
    }
    
}

In image below you can see the swagger page. There, I already filled the authorization. When I sent my request, the authorization is sent in the header ('Authorization: Bearer eyJhb...). However, for some reason it is not reaching the filter. In the line LOG ALL HEADERS, it is showing all headers except by Authorization. enter image description here

But, if I repeat the request using cUrl, the Authorization is received by filter (Image below). enter image description here

This I believe that I did some mistake when I configured @OpenAPIDefinition or @SecurityScheme, but I was not able to find exactly what.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Rafael Afonso
  • 595
  • 1
  • 10
  • 28
  • Are there any errors on the "Console" tab in the dev tools? According to the "Transferred" column on your 1st screenshot, there's a NS_ERROR_DOM_BAD_URI error that prevents the GET request from actually reaching the server. Does your API server [support CORS](https://enable-cors.org/server.html)? – Helen Feb 14 '22 at 09:37
  • 1
    Indeed, there is a error message in console: `Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.207:50000/api/roles. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 400.` I will research how to configure Spring OpenAPI to deal with this problem. – Rafael Afonso Feb 14 '22 at 09:52
  • 1
    OK: I found a solution here: https://stackoverflow.com/questions/42016126/cors-issue-no-access-control-allow-origin-header-is-present-on-the-requested or more exactly, here: https://stackoverflow.com/a/65264237/1659543 – Rafael Afonso Feb 15 '22 at 09:40

0 Answers0