Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I pass JWT token in swagger?? Is this solved yet?? #1812

Closed
pranotiB opened this issue May 12, 2017 · 38 comments
Closed

How can I pass JWT token in swagger?? Is this solved yet?? #1812

pranotiB opened this issue May 12, 2017 · 38 comments
Labels
Milestone

Comments

@pranotiB
Copy link

Im using swagger 2.4.0. Is the issue of using JWT token in swagger solved yet??? I read that, this feature is coming in OenAPI 3.0 version.. Is it right??

@ris58h
Copy link

ris58h commented May 14, 2017

@pranotiB What do you mean "pass JWT token in swagger"?
Maybe you should take a look at #1123

@pranotiB
Copy link
Author

@ris58h No i dont want to ignore web services in spring security.. Im asking how can we add authentication in swagger using spring security? Is it possible to add spring security in swagger??

@ris58h
Copy link

ris58h commented May 15, 2017

@pranotiB Have you tried #1123 (comment) ? It works for me. Just add that SecurityConfiguration Bean to your config and on swagger-ui.html in the top right corner you will see an input for your JWT token (just replace access_token not whole input). It works for 2.5.0 and broken in 2.6.1 (see #1804)

@pranotiB
Copy link
Author

@ris58h Thanks for the reply... yes I have checked this link http://stackoverflow.com/a/37683455 in #1801.. I dont want to ignore it..
And I configured my code accordingly #1804. Api key does appear in text box near to Explore button on swagger ui.. And the api key value is hard coded.
What is the expected output in swagger after configuring the api key??? Im asking because It is not asking me for input or something for api key.. And its hard coded.. Am I missing something?

@ris58h
Copy link

ris58h commented May 15, 2017

@pranotiB Yes, in this way it is hard coded. And you (or other swagger users) should input your (their) valid token in this field. Maybe it's not a best solution but it works and allow user to explore your API.
Could you provide more information about your wokflow and how you see it?

@pranotiB
Copy link
Author

cropped

Its showing my api key value like this..
Didn't get about token you said.. sorry!!

Thanks for the reply!!

@pranotiB
Copy link
Author

pranotiB commented May 15, 2017

@ris58h And even if I want to add token, again i'll add it in my swagger config only.. Right??

@ris58h
Copy link

ris58h commented May 15, 2017

@pranotiB in my swagger config i have
@Bean SecurityConfiguration security() { return new SecurityConfiguration(null, null, null, null, "Bearer access_token", ApiKeyVehicle.HEADER, "Authorization", ","); }
When I go to the swagger UI, I get
image
Then I just replace access_token with my valid JWT token as shown below
image
Now I can use my API endpoints through swagger UI, because JWT token will be sent with each request in Authorization header.

@pranotiB
Copy link
Author

Yes right.. But right now whether I give the access token or not its showing and executing all the web services..
It should not allow me to do so. Is there any setting I have to do for it in StatelessAuthenticationSecurityConfig class or in CORS filter??

@ris58h
Copy link

ris58h commented May 15, 2017

@pranotiB It seems like you should set up your spring security properly. But it isn't within the bounds of the current topic.

@pranotiB
Copy link
Author

@ris58h Spring security is working correctly.. I have checked in postman.. Token is getting generated.. help me with this...

@pranotiB
Copy link
Author

pranotiB commented May 16, 2017

example

see whether i gave token or not its displaying the web services. I tried to add it in antMatchers in security config but its not working..

@ris58h
Copy link

ris58h commented May 16, 2017

@pranotiB What do you want to achieve? Protect swagger UI with Spring security? Add an opportunity to swagger UI to pass JWT token with API calls? Anyway I can't help you without your source code.

@pranotiB
Copy link
Author

@ris58h Im sorry for troubling you. Im just trying to understand, is this how api key works..??

@pranotiB
Copy link
Author

@ris58h I want to protect swagger ui with authentication.. When user will give api key or JWT token then only user will access the web services.. This is what I want to achieve. For this I read about api key. I added api key but all the web services are visible whether i give api key or not..

@ris58h
Copy link

ris58h commented May 17, 2017

@pranotiB It becomes clearer.
How does a user get a JWT token? Does he/she enter username:password? How is the token stored on the user's side? Does the user have access to the token? How the token is passed to the server (header | param | cookie)? How does user get access to swagger ui (username:password or JWT token)? Could you provide your security config?

With Swagger UI when you call your API endpoints, you do AJAX call. If the API is protected with JWT security, you have to add a valid token to each AJAX request. I see 3 options.

  1. One security filter chain for whole application.
    It could be hard to the user to get swagger UI from the browser if you use only JWT security and user doesn't have access to the token.
  2. Ignore swagger in security.
    In this case your swagger ui will be available for everybody, but the rest of the application will be protected (unauthenticated users will get 403 when they try to call the API from swagger UI).
  3. Two separated security filter chains. One for swagger and one for the rest of the application.
    You can give access for swagger ui to the users with BasicAuth for example. The rest of the application will use JWT security.

@pranotiB
Copy link
Author

pranotiB commented May 17, 2017

User gets token after login. It is passed in header. After login user access the web services using token. On front end we have used angular 4. This is what my application is..
On swagger ...
It's not necessary to provide authentication to swagger ui using JWT token only.. If api key provides authentication. That's enough.. I don't want to give access to the REST API's to everybody that's my main intention.
I have secured my application using spring security but for swagger ui im confused how api key is providing authentication..
I hope I have cleared myself..
And configuration is here:
Swagger config

@configuration
@EnableSwagger2
public class SwaggerConfig {

ApiInfo apiInfo() {
	return new ApiInfoBuilder()
			.title("OSAM")
			.description("OSAM")
			.license("Apache 2.0")
			.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
			.termsOfServiceUrl("http://swagger.io/terms/")
			.version("1.0.0").contact(new Contact("","", "pb@gmail.com"))
			.build();
}

@Bean
public Docket api() {
	return new Docket(DocumentationType.SWAGGER_2)
			.select()
			.apis(RequestHandlerSelectors.any())
			.paths(PathSelectors.any())
			.build()
			.enable(true)
			.apiInfo(apiInfo())
			.securityContexts(Lists.newArrayList(securityContext()))
			.securitySchemes(Lists.newArrayList(apiKey()));
}

private ApiKey apiKey() {
	return new ApiKey("AUTHORIZATION", "api_key", "header");
}

 @Bean
 SecurityConfiguration security() {
 return new SecurityConfiguration(
 null,
 null,
 null, // realm Needed for authenticate button to work
 null, // appName Needed for authenticate button to work
 "BEARER ",// apiKeyValue
 ApiKeyVehicle.HEADER,
 "AUTHORIZATION", //apiKeyName
 null);
 }

 private SecurityContext securityContext() {
	    return SecurityContext.builder()
	        .securityReferences(defaultAuth())
	        .forPaths(PathSelectors.regex("/anyPath.*"))
	        .build();
	  }
 
 List<SecurityReference> defaultAuth() {
	    AuthorizationScope authorizationScope
	        = new AuthorizationScope("global", "accessEverything");
	    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
	    authorizationScopes[0] = authorizationScope;
	    return Lists.newArrayList(
	        new SecurityReference("AUTHORIZATION", authorizationScopes));
	  }

In spring configuration I have added

registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");

And in Spring authentication security config I have added like this..

.antMatchers("/configuration/ui","/webjars/**","/swagger-ui.html","/swagger-resources","/configuration/security","/v2/api-docs").permitAll()

But the problem now is this whether I gave API key or not its accessible and it will be because I have permitted it.. But I don't want to.. Whats the correct way to define antMatchers for swagger if I want to use spring security?? Or this is how swagger does not works?? And if I decided to ignore swagger in security then how will be my REST API's are authenticated with api key??

I am using swagger 2.6.1 version..

Thanks a lot (really a lot) for you reply!!!

@dilipkrish
Copy link
Member

@pranotiB have you looked at how jhipster is using it? It may be that the bundled swagger-ui will not work for your use-case and you may need to use it the way jhipster generated projects use it.

@dilipkrish dilipkrish added this to the 2.7.0 milestone May 18, 2017
@jozef-pytko
Copy link

jozef-pytko commented May 23, 2017

Really great help! Instead of providing any clue or example you get "have you looked at how XXX is using it?" and the issue is closed. Fantastic feedback!
I'm using swagger-ui 2.7 and for JWT token it throws "401 : {"error":"invalid_token","error_description":"Cannot convert access token to JSON"} "
(when pasting the response from my oauth2 server to jwt.io there are no problems)

@ris58h
Copy link

ris58h commented May 23, 2017

@jozef-pytko When did you get this message? When you accessed swagger-ui or when you called your API from swagger-ui?

@jozef-pytko
Copy link

jozef-pytko commented May 23, 2017

@ris58h Hi. Thank you for your help.
The answer to your question is: neither of those two. I can access swagger-ui. I get the error when I try try to authorize (get JWT Oauth2 token) with swagger-ui to be able to call my API.

It goes like this:

  1. I have a Oauth2 spring boot authorization app that generates JWT tokens. I'm using standard @EnableAuthorizationServer. The server uses password flow. So when I POST to eg.
    http://client:client_key@localhost:8090/oauth/token?grant_type=password&username=dev&password=dev&scope=all my server returns JWT Token back:
{
  "access_token": "XXXXXXXXXXXXXXXXXXXXXX",
  "token_type": "bearer",
  "refresh_token": "XXXXXXXXXXXXXXXXXXXXXXXX",
  "expires_in": 89999,
  "scope": "all",
  "jti": "d9047694-ef59-4661-8485-3157448d85ff"
}

All standard stuff. When I copy paste the access_token field to jwt.io it parses it with no errors.

  1. My REST endpoints are secured with oauth2. I'm using @EnableResourceServer. Everything works fine.

  2. I would like to use springfox for generating swagger-ui.html. So I marked my request mapping method with:

    @ApiOperation(
            value = "Get All",
            produces = APPLICATION_JSON_VALUE
            , authorizations = {@Authorization(value = SwaggerConfiguration.securitySchemaOAuth2, scopes =
            {@AuthorizationScope(scope = SwaggerConfiguration.authorizationScopeGlobal, description = SwaggerConfiguration.authorizationScopeGlobalDesc)})}
    )

and added in swagger config:

    private OAuth securitySchema() {
        List<AuthorizationScope> authorizationScopeList = Collections.singletonList(new AuthorizationScope(authorizationScopeGlobal, authorizationScopeGlobalDesc));
        ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant = new ResourceOwnerPasswordCredentialsGrant("http://localhost:8090/oauth2app/oauth/token");
        List<GrantType> grantTypes = Collections.singletonList(resourceOwnerPasswordCredentialsGrant);
        OAuth oAuth = new OAuth(securitySchemaOAuth2, authorizationScopeList, grantTypes);
        return oAuth;
    }

and I am using it as

.securitySchemes(Collections.singletonList(securitySchema()))

Seems to work fine. On swagger-ui I can see the 'Authorize' button.

image

I fill the data. Browser makes the right request, gets the JWT token back from authorization app and throws an error:

image

Any ideas?

@ris58h
Copy link

ris58h commented May 23, 2017

@jozef-pytko Sorry, but I don't use Oauth2 and swagger-ui 2.7 in my app. Did you debug?

@dilipkrish
Copy link
Member

@jozef-pytko AFAIK JWT is not supported in the spec and neither is it supported in swagger ui as evidenced by this issue. On top of that the most popular and adequately supported library that uses JWT/swagger-ui and springfox is jhipster. They have a cusomtized swagger-ui that supports looking up/loading JWT tokens from local storage and works just like a bearer token.

Now JWT as a workflow is not supported by the standard (uncustomized) swagger-ui. You have a couple of options.

  1. You'd have to do the token dance and load the JWT token in the server side. And instead of using the OAuth scheme you'd use an API Key mechanism and constructor your own api key Bearer {jwttoken}. Downside is that the UI now works only with one JWT token and not user authenticated.
  2. You customize the swagger-ui and NOT use the one that comes with the library. In which case jhipster is a great candidate to emulate.

Lastly, regarding your comment

Really great help! Instead of providing any clue or example you get "have you looked at how XXX is using it?" and the issue is closed. Fantastic feedback!

Its not that we don't want to help. I try to help where I can on top of maintaining this library, managing issues, responding to questions, even if its entitled. I speak for myself the many other contributors to this library that we do this because of the spirit of open source and our passion. There is only so much time in the day and my time IS valuable. Please remember This is OSS. No one pays me to maintain this library, and Its needs to be sustainable for ME first and foremost.

Really its about finding the solutions and sharing back with the community and THAT would be much appreciated and useful.

@pranotiB
Copy link
Author

Instead of making your valuable time to reply the queries and problems, make sure the problems does not occur in the first place. And you can easily achieve this by providing a good documentation on your site.. That would be a great help!! Your product is great but documentation... Sorry to say this..

@dilipkrish
Copy link
Member

@pranotiB No need to be sorry. That is absolutely the way to do it.

Let me try to explain the process just so you have an appreciation of the work involved. Suggestions are welcome to improve the process.

I try to do the following:

  • answer questions briefly (and quickly like here) if the solution is beyond the scope of this library. In this case supporting JWT is definitely not in scope for this library.
  • We rely on Google as it does a great job of searching github for issues. So invariable (and organically) someone will come and see all this ☝️great discussion.
  • Sometimes if someone has solved the problem they will contribute the solution, here is a great example.
  • When someone is kind enough to contribute back and its useful for either trouble shooting, I tag the issue as can-use-for-docs.
  • Before every release those tags are review and go back to the documentation in some form or other... Have you seen the trouble shooting section?
  • If the solution warrants an example I also update the springfox-demos application so that its a template for solving the problem.
  • Lastly there is also stackoverflow

Now remember this is all just to answer questions and update the documentation based on queries!!

In addition there are feature requests, bug fixes and maintenance that make sure the problems does not occur in the first place.

@gasperlf
Copy link

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

@Bean
SecurityConfiguration security() {
    return new SecurityConfiguration(null, null, null, // realm Needed for authenticate button to work
            null, // appName Needed for authenticate button to work
            "  ", // apiKeyValue
            ApiKeyVehicle.HEADER, "Authorization", // apiKeyName
            null);
}

and it is work well

@goodlifeinc
Copy link

That has helped me a lot - https://springfox.github.io/springfox/docs/current/

@krmao
Copy link

krmao commented Dec 8, 2017

problem with 2.7.0

change version back to 2.5.0
and copy token to right-top-input and don't click the button "explore" is ok
----ps
what is the function about button 'explore' ?

ok with version 2.5.0

image
image

@paulocdf
Copy link

I'm having trouble understanding why "Authorization: Bearer __" is not being sent in my api. I have the following configuration:

private ApiKey apiKey() {
		return new ApiKey(
				"Authorization", // name: My key - Authorization
				"api_key", // keyname: api_key
				"header");
	}


@Bean
	SecurityConfiguration security() {
		return new SecurityConfiguration(
				null, null, null,
				"Docserver2_fwk", // app name
				"BEARER", // api key value
				ApiKeyVehicle.HEADER, "Authorization", ",");
	}

image

And the curl being sent is:

image

It seems I am unable to send "Authorization Bearer: Token" in springfox (2.5.0), is this possible?, is it a known problem?

@dilipkrish
Copy link
Member

@paulocdf Its possible its a bug, would you mind creating a new issue for this?

@dhirendragit
Copy link

dhirendragit commented Feb 15, 2018

@paulocdf and @dilipkrish # I am also facing same issue OAuth2 reference token not showing up in the Value text box. Could you please let me know if issue has been fixed or any workaround to set reference token with Bearer string in the Value text box automatically.

using springfox 2.8.0:
compile "io.springfox:springfox-swagger2:2.8.0"
compile "io.springfox:springfox-swagger-ui:2.8.0"

For time being entering token with Bearer string in the Value text box but I want to automate it, please advise.

@mhersc1
Copy link

mhersc1 commented Mar 5, 2018

Hi every one
I found a bug for this version 2.8.0, I use the following libraries springfox-swagger2 and springfox-swagger-ui (2.8.0) from Maven.

I attach the code of my application

//Swagger Config Class
@configuration
@enableswagger2
public class SwaggerConfig {
@bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("xxxx.yyyy.zzzzz"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo())
.securitySchemes(Collections.singletonList(apiKey()))
.securityContexts(Collections.singletonList(securityContext()));
}

private SecurityContext securityContext() {
    return SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.regex("/anyPath.*"))
            .build();
}

List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope
            = new AuthorizationScope("global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return Collections.singletonList(new SecurityReference("Bearer", authorizationScopes));
}
@bean
public ApiListingScannerPlugin listingScanner() {
return new SwaggerManualApiPlugin();
}
}

//SwaggerManualApiPlugin
public class SwaggerManualApiPlugin implements ApiListingScannerPlugin {
@override
public List apply(DocumentationContext context) {
return new ArrayList(
Arrays.asList(
new ApiDescription(
"/fondos/generartoken",
"Generar Token Basic OAUTH",
Arrays.asList(
new OperationBuilder(
new CachingOperationNameGenerator())
.authorizations(new ArrayList())
.codegenMethodNameStem("basicAuth0001")
.method(HttpMethod.POST)
.notes("Endpoint responsable de la Autenticacion Básica de XXXXXX")
.parameters(
Arrays.asList(
new ParameterBuilder()
.description("Basic Auth")
.type(new TypeResolver().resolve(String.class))
.name("Authorization")
.defaultValue("Basic XXXXXXXXX")
.parameterType("header")
.parameterAccess("access")
.hidden(true)
.required(true)
.modelRef(new ModelRef("string"))
.build(),
new ParameterBuilder()
.description("Tipo de Grant")
.type(new TypeResolver().resolve(String.class))
.name("grant_type")
.defaultValue("password")
.required(true)
.hidden(true)
.parameterType("query")
.parameterAccess("access")
.modelRef(new ModelRef("string"))
.build(),
new ParameterBuilder()
.description("Tipo de Documento")
.type(new TypeResolver().resolve(String.class))
.name("tipoDocumento")
.parameterType("query")
.parameterAccess("access")
.required(true)
.modelRef(new ModelRef("string"))
.build(),
new ParameterBuilder()
.description("Numero de Documento")
.type(new TypeResolver().resolve(String.class))
.name("numeroDocumento")
.parameterType("query")
.parameterAccess("access")
.required(true)
.modelRef(new ModelRef("string"))
.build(),
new ParameterBuilder()
.description("Origen del canal")
.type(new TypeResolver().resolve(String.class))
.name("origen")
.defaultValue("web")
.parameterType("query")
.parameterAccess("access")
.required(true)
.modelRef(new ModelRef("string"))
.build(),
new ParameterBuilder()
.description("Codigo del canal")
.type(new TypeResolver().resolve(String.class))
.name("canal")
.defaultValue("PLD000501")
.parameterType("query")
.parameterAccess("access")
.required(true)
.modelRef(new ModelRef("string"))
.build()))
.build()),
false)));
}

@Override
public boolean supports(DocumentationType delimiter) {
    return DocumentationType.SWAGGER_2.equals(delimiter);
}
}

The problem here is that this new operation is creating is not showing response on version 2.8.0.
I tried with version 2.7.0 and if it's showing response, however when I try with other operation the new operation's response dissapears, but this is not problem for me.

image

Maybe I forgot any configuration, if so, throw me a cable.
Thanks in advance.

@rajjaiswalsaumya
Copy link

somebody pls tell me how to use this with custom jwt impl and spring security with spring boot?

@jmurretxactly
Copy link

jmurretxactly commented Nov 2, 2018

I have this working with Spring Security with Swagger UI 2.8.0 with a basic approach.

I took the approach of 1) leaving my api routes secured by Authorization header and 2) swagger ui being unrestricted. (Some answers here keep the whole api secured and that seems to be harder and more confusing)

So related to above points. Here is

  1. Securing api but opening up Swagger (in Scala...shortened to only show essentials...add your additional configurations as needed):
@Configuration
@EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @throws[Exception]
  override def configure(http: HttpSecurity): Unit = {
    http
      .authorizeRequests
        .antMatchers("/", "/csrf", "/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**").permitAll //open up swagger ui
        .anyRequest.authenticated  //rest of api
  }
}
  1. Configuring parameter in Swagger UI to allow me to pass the Authorization token. Here is my SwaggerConfig (in Scala):
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Bean
import org.springframework.web.bind.annotation.RestController
import springfox.documentation.swagger2.annotations.EnableSwagger2
import springfox.documentation.spring.web.plugins.Docket
import springfox.documentation.spi.DocumentationType
import springfox.documentation.builders.{ApiInfoBuilder, PathSelectors, RequestHandlerSelectors}
import springfox.documentation.service.ApiInfo
import springfox.documentation.builders.ParameterBuilder
import springfox.documentation.schema.ModelRef
import springfox.documentation.service.Parameter
import java.util


@Configuration
@EnableSwagger2
class SwaggerConfig {
  @Bean
  def api(): Docket = {
    //Adding Header
    val paramBuilder = new ParameterBuilder
    val params = new util.ArrayList[Parameter]

    params.clear()

    paramBuilder.name("Authorization").modelRef(new ModelRef("string"))
      .parameterType("header")
      .required(false).build
    params.add(paramBuilder.build)
    new Docket(DocumentationType.SWAGGER_2)
      .globalOperationParameters(params) //<- this is the true line that hooks it up 
      .select()
      .apis(RequestHandlerSelectors.withClassAnnotation(classOf[RestController]))
      .paths(PathSelectors.any)
      .build.apiInfo(apiInfo())
  }

  def apiInfo(): ApiInfo =
    new ApiInfoBuilder().title("XXX API")
      .version("0.0.1")
      .contact("My Team")
      .build()
}

This is what it looks like in the UI and it does send the bearer token successfully.
screen shot 2018-11-02 at 7 23 16 am

I hope this helps someone else.

@hijazyr
Copy link

hijazyr commented Dec 27, 2018

@jmurretxactly Thanks for the awesome response. So far the most authentic answer to the problem, rather the best, just that its in Scala :), just kidding, one can easily translate it to Java.

Here's the same version of the code (well almost) in Java:

`import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.ApiKeyVehicle;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@configuration
@EnableSwagger2
public class SwaggerConfiguration {

@Bean
public Docket api()
{
	ParameterBuilder paramBuilder = new ParameterBuilder();
	List<Parameter> params = new ArrayList<>();
	paramBuilder.name("Authorization").modelRef(new ModelRef("string"))
	.parameterType("header")
	.required(false)
	.build();
	params.add(paramBuilder.build());
	return new Docket(DocumentationType.SWAGGER_2)
			.globalOperationParameters(params)
			.select()
			.apis(RequestHandlerSelectors.any())
			.paths(PathSelectors.any())
			.build()
			.apiInfo(apiInfo())				
			.consumes(new HashSet<String>(Arrays.asList("application/json")))
			.produces(new HashSet<String>(Arrays.asList("application/json")));
}

private ApiInfo apiInfo() {
    return new ApiInfo(
      "My API", 
      "My API desc", 
      "1.0", 
      "Terms of service", 
      new Contact("hijazyr", "", ""), 
      "License of API", "API license URL", Collections.emptyList());
}

}`

@alisonatwork
Copy link

I posted a simple solution to this in #2194 if anyone is still interested. You can use the Authorize feature built in to Swagger UI to set the header and then have it applied to all requests.

@arunkumaranand
Copy link

I posted a simple solution to this in #2194 if anyone is still interested. You can use the Authorize feature built in to Swagger UI to set the header and then have it applied to all requests.

@alisonatwork , Thanks a lot!!

@OscarHMG
Copy link

OscarHMG commented Mar 4, 2020

@alisonatwork @hijazyr THANKS A LOT!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests