-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
Comments
@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?? |
@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) |
@ris58h Thanks for the reply... yes I have checked this link http://stackoverflow.com/a/37683455 in #1801.. I dont want to ignore it.. |
@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. |
@ris58h And even if I want to add token, again i'll add it in my swagger config only.. Right?? |
@pranotiB in my swagger config i have |
Yes right.. But right now whether I give the access token or not its showing and executing all the web services.. |
@pranotiB It seems like you should set up your spring security properly. But it isn't within the bounds of the current topic. |
@ris58h Spring security is working correctly.. I have checked in postman.. Token is getting generated.. help me with this... |
@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. |
@ris58h Im sorry for troubling you. Im just trying to understand, is this how api key works..?? |
@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.. |
@pranotiB It becomes clearer. 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.
|
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.. @configuration
In spring configuration I have added registry.addResourceHandler("swagger-ui.html") 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!!! |
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! |
@jozef-pytko When did you get this message? When you accessed swagger-ui or when you called your API from swagger-ui? |
@ris58h Hi. Thank you for your help. It goes like this:
All standard stuff. When I copy paste the access_token field to jwt.io it parses it with no errors.
@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. I fill the data. Browser makes the right request, gets the JWT token back from authorization app and throws an error: Any ideas? |
@jozef-pytko Sorry, but I don't use Oauth2 and swagger-ui 2.7 in my app. Did you debug? |
@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.
Lastly, regarding your comment
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. |
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.. |
@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:
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. |
private ApiKey apiKey() {
and it is work well |
That has helped me a lot - https://springfox.github.io/springfox/docs/current/ |
I'm having trouble understanding why "Authorization: Bearer __" is not being sent in my api. I have the following configuration:
And the curl being sent is: It seems I am unable to send "Authorization Bearer: Token" in springfox (2.5.0), is this possible?, is it a known problem? |
@paulocdf Its possible its a bug, would you mind creating a new issue for this? |
@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: For time being entering token with Bearer string in the Value text box but I want to automate it, please advise. |
Hi every one 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. Maybe I forgot any configuration, if so, throw me a cable. |
somebody pls tell me how to use this with custom jwt impl and spring security with spring boot? |
@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 org.springframework.context.annotation.Bean; import springfox.documentation.builders.ParameterBuilder; @configuration
}` |
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!! |
@alisonatwork @hijazyr THANKS A LOT!! |
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??
The text was updated successfully, but these errors were encountered: