Skip to content

Commit

Permalink
Fix swagger Authorization header
Browse files Browse the repository at this point in the history
  • Loading branch information
murraco committed Jul 19, 2020
1 parent c341ba4 commit 6b076ad
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
32 changes: 27 additions & 5 deletions src/main/java/murraco/configuration/SwaggerConfig.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package murraco.configuration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.springframework.context.annotation.Bean;
Expand All @@ -14,9 +15,12 @@
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.Tag;
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;

Expand All @@ -33,22 +37,40 @@ public Docket api() {
.build()//
.apiInfo(metadata())//
.useDefaultResponseMessages(false)//
.securitySchemes(new ArrayList<>(Arrays.asList(new ApiKey("Bearer %token", "Authorization", "Header"))))//
.securitySchemes(Collections.singletonList(apiKey()))
.securityContexts(Collections.singletonList(securityContext()))
// .securitySchemes(Arrays.asList(new ApiKey("Bearer %token", "Authorization", "Header")))//
.tags(new Tag("users", "Operations about users"))//
.tags(new Tag("ping", "Just a ping"))//
.genericModelSubstitutes(Optional.class);

}

private ApiInfo metadata() {
return new ApiInfoBuilder()//
.title("JSON Web Token Authentication API")//
.description(
"This is a sample JWT authentication service. You can find out more about JWT at [https://jwt.io/](https://jwt.io/). For this sample, you can use the `admin` or `client` users (password: admin and client respectively) to test the authorization filters. Once you have successfully logged in and obtained the token, you should click on the right top button `Authorize` and introduce it with the prefix \"Bearer \".")//
.description("This is a sample JWT authentication service. You can find out more about JWT at [https://jwt.io/](https://jwt.io/). For this sample, you can use the `admin` or `client` users (password: admin and client respectively) to test the authorization filters. Once you have successfully logged in and obtained the token, you should click on the right top button `Authorize` and introduce it with the prefix \"Bearer \".")//
.version("1.0.0")//
.license("MIT License").licenseUrl("http://opensource.org/licenses/MIT")//
.contact(new Contact(null, null, "mauriurraco@gmail.com"))//
.build();
}

private ApiKey apiKey() {
return new ApiKey("Authorization", "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("Authorization", authorizationScopes));
}

}
7 changes: 4 additions & 3 deletions src/main/java/murraco/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
import murraco.dto.UserDataDTO;
import murraco.dto.UserResponseDTO;
import murraco.model.User;
Expand Down Expand Up @@ -59,7 +60,7 @@ public String signup(@ApiParam("Signup User") @RequestBody UserDataDTO user) {

@DeleteMapping(value = "/{username}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation(value = "${UserController.delete}")
@ApiOperation(value = "${UserController.delete}", authorizations = { @Authorization(value="apiKey") })
@ApiResponses(value = {//
@ApiResponse(code = 400, message = "Something went wrong"), //
@ApiResponse(code = 403, message = "Access denied"), //
Expand All @@ -72,7 +73,7 @@ public String delete(@ApiParam("Username") @PathVariable String username) {

@GetMapping(value = "/{username}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation(value = "${UserController.search}", response = UserResponseDTO.class)
@ApiOperation(value = "${UserController.search}", response = UserResponseDTO.class, authorizations = { @Authorization(value="apiKey") })
@ApiResponses(value = {//
@ApiResponse(code = 400, message = "Something went wrong"), //
@ApiResponse(code = 403, message = "Access denied"), //
Expand All @@ -84,7 +85,7 @@ public UserResponseDTO search(@ApiParam("Username") @PathVariable String usernam

@GetMapping(value = "/me")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_CLIENT')")
@ApiOperation(value = "${UserController.me}", response = UserResponseDTO.class)
@ApiOperation(value = "${UserController.me}", response = UserResponseDTO.class, authorizations = { @Authorization(value="apiKey") })
@ApiResponses(value = {//
@ApiResponse(code = 400, message = "Something went wrong"), //
@ApiResponse(code = 403, message = "Access denied"), //
Expand Down

0 comments on commit 6b076ad

Please sign in to comment.