question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Document springfox oauth2

See original GitHub issue

springfox version 2.5.0

I use http://localhost:8080/clbs/swagger-ui.html to acess swagger api,first i need to login(http://localhost:8080/clbs,this is our system login page),provide user name and password,login the system,then i can access swagger apis,but when i click try it out,it appears the error:401,it is click to authenticate button here ,but nothing happened when i click it,doesnt pop window. i dont know how to config,what i expect is when click authenticate button,input username and pwd,then get token from oauth2,then swagger ui will save this token automatically ,next time i run try it out ,the operation will be authorized. Anybody could help me ,tell me how to solve this issue,thanks a lot. this is swagger config:

@EnableSwagger2  
@ComponentScan(basePackages = {"com.zw.swagger.controller"})
@Configuration
public class SwaggerConfig {  
	public static final String securitySchemaOAuth2 = "oauth2schema";
	public static final String authorizationScopeGlobal = "global";
	public static final String authorizationScopeGlobalDesc ="accessEverything";
   @Bean  
   public Docket createRestApi() {  
	   List s = new ArrayList();
	    s.add(securitySchema());
	    List d= new ArrayList();
	    d.add(securityContext());
       return new Docket(DocumentationType.SWAGGER_2)  
               .apiInfo(apiInfo())  
               .select()  
               .apis(RequestHandlerSelectors.basePackage("com.zw.swagger.controller"))  
               .paths(PathSelectors.any())  
               .build()
               .securitySchemes(s)
               .securityContexts(d);  
   }  
 
   private ApiInfo apiInfo() {  
       return new ApiInfoBuilder()  
               .title("Spring 中使用Swagger2构建RESTful APIs")  
               .termsOfServiceUrl("")  
               .contact("中位科技")  
               .version("3.3")  
               .build();  
   }  
   private OAuth securitySchema() {
	    AuthorizationScope authorizationScope = new AuthorizationScope(authorizationScopeGlobal, authorizationScopeGlobal);
	    LoginEndpoint loginEndpoint = new LoginEndpoint("http://localhost:8080/clbs/swagger-ui.html");
	    GrantType grantType = new ImplicitGrant(loginEndpoint, "access_token");
	    List s = new ArrayList();
	    s.add(authorizationScope);
	    List d = new ArrayList();
	    d.add(grantType);
	    return new OAuth(securitySchemaOAuth2, s, d);
	}

	private SecurityContext securityContext() {
	    return SecurityContext.builder()
	            .securityReferences(defaultAuth())
	            .forPaths(PathSelectors.any())
	            .build();
	}



	private List<SecurityReference> defaultAuth() {
	    AuthorizationScope authorizationScope
	            = new AuthorizationScope(authorizationScopeGlobal, authorizationScopeGlobalDesc);
	    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
	    authorizationScopes[0] = authorizationScope;
	    List d = new ArrayList();
	    d.add(new SecurityReference(securitySchemaOAuth2, authorizationScopes));
	    return new ArrayList(
	            d);
	}

this is spring_security.xml:

<sec:http pattern="/oauth/token" create-session="stateless"
              authentication-manager-ref="oauth2AuthenticationManager"
              use-expressions="false">
        <sec:intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY"/>
        <sec:anonymous enabled="false"/>
        <sec:http-basic entry-point-ref="oauth2AuthenticationEntryPoint"/>
        <sec:custom-filter ref="clientCredentialsTokenEndpointFilter"
                           before="BASIC_AUTH_FILTER"/>
        <sec:access-denied-handler ref="oauth2AccessDeniedHandler"/>
        <sec:csrf disabled="true"/>
    </sec:http>

    <sec:http pattern="/swagger/**" create-session="never"
              entry-point-ref="oauth2AuthenticationEntryPoint"
              access-decision-manager-ref="oauth2AccessDecisionManager"
              use-expressions="false">
        <sec:anonymous enabled="false"/>
        <sec:intercept-url pattern="/swagger/**" access="IS_AUTHENTICATED_FULLY,SCOPE_READ"/>
        <sec:custom-filter ref="mobileResourceServer"
                           before="PRE_AUTH_FILTER"/>
        <sec:access-denied-handler ref="oauth2AccessDeniedHandler"/>
        <sec:csrf disabled="true"/>
    </sec:http>

this is swagger controller:

@RestController
@RequestMapping("/swagger/m/basicinfo/equipment/device")
public class SwaggerDeviceController {
    @RequestMapping(value = {"/list"}, method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "devie", notes = "")
	@ApiImplicitParams(value = { 
            @ApiImplicitParam(name = "page", value = "page", required = true, paramType = "query",dataType = "Long",defaultValue = "1"),
            @ApiImplicitParam(name = "limit", value = "pagecount", required = true, paramType = "query",dataType = "Long",defaultValue = "20"),
            @ApiImplicitParam(name = "simpleQueryParam", value = "query", required = false, paramType = "query",dataType = "String"),
	})
    public PageGridBean getListPage(final DeviceQuery query,HttpResponse response) throws BusinessException {
		response.setHeader("Access-Control-Allow-Origin","*");
		response.setHeader("Access-Control-Allow-Methods","POST");
		response.setHeader("Access-Control-Max-Age","10000");
		response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
	....

image

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
kidshgcommented, Mar 10, 2017

@dilipkrish which doc?Could you send me one? i 've read the doc on web site,but got nothing information about swagger under oauth2 .

0reactions
dilipkrishcommented, Jan 13, 2018

Added a sample project/documentation as part of #1913

Read more comments on GitHub >

github_iconTop Results From Across the Web

Springfox Reference Documentation - GitHub Pages
Springfox works by examining an application, once, at runtime to infer API semantics based on spring configurations, class structure and various ...
Read more >
Setting Up Swagger 2 with a Spring REST API - Baeldung
Learn how to document a Spring REST API using Swagger 2. ... is used to describe how our API is secured (Basic Authentication,...
Read more >
How to configure oAuth2 with password flow with Swagger ui ...
After 8 months, finally the password flow is supported in Swagger UI, here is the final code and settings which works for me:...
Read more >
OAuth2 authorization - Google Groups
I'm having problems with swagger documentation for API endpoints which have the @PreAuthorize annotation (we use spring framework and OAuth2 for ...
Read more >
OAuth 2.0 configuration - Swagger Documentation
You can configure OAuth 2.0 authorization by calling the initOAuth method. Property name, Docker variable, Description. clientId, OAUTH_CLIENT_ID, Default ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found