How send token to header of Swagger - spring-boot

I have Spring Boot application. And I want to integrate swagger in my project.
I am using springfox 2.7.0 and auth0 for authentication on swagger, but I have problem with send id_token from auth0 to header of swagger.
This is my code for Swagger configuration:
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("name.web"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo())
.securitySchemes(Collections.singletonList(securitySchema()));
}
private OAuth securitySchema() {
List<AuthorizationScope> authorizationScopeList = new ArrayList<>();
authorizationScopeList.add(new AuthorizationScope("openid", "access all"));
List<GrantType> grantTypes = new ArrayList<>();
final TokenRequestEndpoint tokenRequestEndpoint = new TokenRequestEndpoint("https://bovinet.auth0.com/authorize", "clientId", "secretKey");
final TokenEndpoint tokenEndpoint = new TokenEndpoint("http://server.com/oauth/token", "id_token");
AuthorizationCodeGrant authorizationCodeGrant = new
AuthorizationCodeGrant(tokenRequestEndpoint, tokenEndpoint);
grantTypes.add(authorizationCodeGrant);
OAuth oAuth = new OAuth("oauth2", authorizationScopeList, grantTypes);
return oAuth;
}
private ApiInfo apiInfo() {
#SuppressWarnings("deprecation")
ApiInfo apiInfo = new ApiInfo(
"Name", "", "", "", "", "", "");
return apiInfo;
}
#Bean
SecurityConfiguration security() {
return new SecurityConfiguration(
"clientId",
"secretKey",
"test-app-realm",
"https://server.com",
"api_key",
ApiKeyVehicle.HEADER,
"Authorization",
"," /*scope separator*/);
}
When I open console for swagger-ui.htm page I can see id_token in response of /oauth/token request but I don't know how put that token in header of swagger.
Can somebody please help me to resolve this problem?

Related

get the "instance_url" in the oauth2 salesforce response and use it in the webclient baseurl

I use a Bean webclient for my connection with salesforce
I created a configuration class with these 2 methods.
#Configuration
public class salesForceConfig {
#Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientService authorizedClientService
) {
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder().password().build();
AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager = new AuthorizedClientServiceOAuth2AuthorizedClientManager (clientRegistrationRepository, authorizedClientService );
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
authorizedClientManager.setContextAttributesMapper(oAuth2AuthorizeRequest -> {
if (SALESFORCE.equals(oAuth2AuthorizeRequest.getClientRegistrationId())) {
return Map.of(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, SALESFORCE_USERNAME,OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, SALESFORCE_PASSORD
);
}
return null;
});
return authorizedClientManager;
}
#Bean
public WebClient salesforceWebClient(OAuth2AuthorizedClientManager authorizedClientManager) {
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
oauth2Client.setDefaultClientRegistrationId(SALESFORCE);
return WebClient.builder()
.baseUrl(SALESFORCE_BASE_PATH)
.apply(oauth2Client.oauth2Configuration())
.build();
}
}
`
during the authentication, I have a message with the token and other information like instance_url.
`{
"access_token": "xxxxx",
"instance_url": "https://xxxx.salesforce.com",
"id": "https://login.salesforce.com/id/xxxxxx",
"token_type": "Bearer",
"issued_at": "xxxx",
"signature": "xxxx"
}
I want to change the webclient baseurl address based on instance_url.
does anyone have any idea how to do this.

Swagger Ui hangs for api endpoint in spring boot

My client api endpoint is not loading in swagger UI as shown in the image what I need to do? It always show loading icon when I click on any client controller api like get,post
Please post answer Thank You
see picture
SwaggerConfig.groovy
#Configuration
#EnableSwagger2
class SwaggerConfig {
#Bean
Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any()
.paths(PathSelectors.any())
.build().apiInfo(metaData())
}
private ApiInfo metaData() {
return new ApiInfoBuilder()
.title("Swagger Example")
.description("\"Swagger configuration for application \"")
.version("1.1.0")
.license("Apache 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"")
.build()
}
}
ClientController.groovy
#RestController
#RequestMapping('/client')
class ClientController {
#Autowired
ClientService clientService
#GetMapping('/')
ResponseEntity<List<Client>> getAllClients() {
List<Client> clients = clientService.getAllClients()
return new ResponseEntity<>(clients, HttpStatus.OK)
}
#GetMapping('/{clientId}')
ResponseEntity<Client> getClientById(#PathVariable("clientId") Integer clientId) {
return new ResponseEntity<>(clientService.getClientById(clientId), HttpStatus.OK)
}
#PostMapping('/create')
ResponseEntity<Client> createClient(#RequestBody Client client) {
return new ResponseEntity<>(clientService.addClient(client), HttpStatus.CREATED)
}
#PutMapping('/update/{clientId}')
ResponseEntity<Client> updateClient(#PathVariable("clientId") Integer clientId, #RequestBody Client client) {
clientService.updateClient(client, clientId)
return new ResponseEntity<>(clientService.getClientById(clientId), HttpStatus.OK)
}
#DeleteMapping('/delete/{clientId}')
ResponseEntity<Client> deleteClient(#PathVariable("clientId") Integer clientId) {
clientService.deleteClientById(clientId)
return new ResponseEntity<>(HttpStatus.NO_CONTENT)
}
}

Example of Swagger Configuration with Security in Spring Boot

Someone has an example of swagger security with spring boot?
My docket config it is like this:
#Bean
public Docket userApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.paths(PathSelectors.any())
.build()
.apiInfo(metaData());
}
to configure swagger with security you should set the securityContexts like this :
private final TypeResolver typeResolver;
// constructor
public SwaggerConfig(TypeResolver typeResolver) {
this.typeResolver = typeResolver;
}
#Bean
public Docket apiBatch() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("path.to.package"))
.paths(PathSelectors.any())
.build()
.securitySchemes(Lists.newArrayList(apiKey()))
.securityContexts(Collections.singletonList(securityContext()))
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title)
.description(description)
.version(version)
.build();
}
/**
* add as header the Authorization header
*
* #return
*/
private ApiKey apiKey() {
return new ApiKey("apiKey", "Authorization", "header");
}
/**
* demand the authorization for access on /api/v1/**
*
* #return
*/
private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/api/v1.*")).build();
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope(
"global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Collections.singletonList(new SecurityReference("apiKey",
authorizationScopes));
}
private AlternateTypeRule getAlternateTypeRule(Type sourceType, Type sourceGenericType,
Type targetType, Type targetGenericType) {
return AlternateTypeRules.newRule(typeResolver.resolve(sourceType, sourceGenericType),
typeResolver.resolve(targetType, targetGenericType));
}
Edit
I've added the TypeResolver property of fasterxml classmate library ( compile group: 'com.fasterxml', name: 'classmate', version: '1.3.1' )
Note that SwaggerConfig is the config class name

Springboot swagger ui with Bearer token

I use Bearer token to access my api. so I configure my swagger just like this:
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("br.com.lumera.intimacaoapi.controller"))
.paths(PathSelectors.any())
.build()
.securitySchemes(Lists.newArrayList(apiKey()))
.securityContexts(Arrays.asList(securityContext()));
}
private ApiKey apiKey() {
return new ApiKey("Bearer", "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("Bearer",
authorizationScopes));
}
}
but for every request my user must input Bearer <>. It's possible to I configure the swagger to put automatic the 'Bearer ' before the token that my user insert?
tks
One work around for this issue can be setting "Bearer " as default value as shown below
public ResponseEntity method_name(#ApiParam(defaultValue = "Bearer ") String auth) { }
This code will show "Bearer " as default value in token input field box. You can add the token after the bearer in the input field box.

From swagger editor able to get the JWT auth token, but from application which enabled swagger-ui using springfox is not working

Tested my auth server from swagger editor and is working fine. I'm able to get the token and authorization is happening without any issues. But, when I tried to integrate it with my web service where swagger UI is enabled using springfox dependencies is not working.
Success form swagger editor
Failed from application
Noticed that in the failed case, swagger UI is sending only a single POST request, but swagger editor had an OPTIONS & POST request to get the token.
Suspected CROS filter initially, so I took my swagger json and tested in swagger editor and it worked.
My auth server and resource server with application is also working fine when tested via curl.
Sample auth server and resource server is this:- https://github.com/ranjithap7576/OAuth2-JWT
And swagger configuration is below
#Configuration
#EnableSwagger2
public class SwaggerConfigNew {
#Value("${security.jwt.resource-ids}")
private String clientId;
#Value("${security.signing-key}")
private String clientSecret;
#Value("${security.oauth2.authserver}")
private String authLink;
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("my.package")).build().groupName("test")
.directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)
.securitySchemes(Collections.singletonList(securitySchema()))
.securityContexts(Collections.singletonList(securityContext()));
}
private OAuth securitySchema() {
List<AuthorizationScope> authorizationScopeList = newArrayList();
authorizationScopeList.add(new AuthorizationScope("read", "read all"));
authorizationScopeList.add(new AuthorizationScope("trust", "trust all"));
authorizationScopeList.add(new AuthorizationScope("write", "access all"));
List<GrantType> grantTypes = newArrayList();
GrantType creGrant = new ResourceOwnerPasswordCredentialsGrant(authLink + "/oauth/token");
grantTypes.add(creGrant);
return new OAuth("oauth2schema", authorizationScopeList, grantTypes);
}
#Bean
UiConfiguration uiConfig() {
return new UiConfiguration("validatorUrl", // url
"none", // docExpansion => none | list
"alpha", // apiSorter => alpha
"schema", // defaultModelRendering => schema
UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, // enableJsonEditor => true | false
true, // showRequestHeaders => true | false
60000L); // requestTimeout => in milliseconds, defaults to null (uses jquery xh timeout)
}
#Bean
public SecurityConfiguration securityInfo() {
return new SecurityConfiguration(clientId, clientSecret, "", "", "", ApiKeyVehicle.HEADER, "", " ");
}
private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.ant("/user/**"))
.build();
}
private List<SecurityReference> defaultAuth() {
final AuthorizationScope[] authorizationScopes = new AuthorizationScope[3];
authorizationScopes[0] = new AuthorizationScope("read", "read all");
authorizationScopes[1] = new AuthorizationScope("trust", "trust all");
authorizationScopes[2] = new AuthorizationScope("write", "write all");
return Collections.singletonList(new SecurityReference("oauth2schema", authorizationScopes));
}
// #Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
I'm using springfox 2.7.0

Resources