Swagger-ui with Spring security











up vote
0
down vote

favorite












I have a simple REST application with authentication service. I tried to add swagger and swagger-ui to it, but I can only see my endpoints in /v2/api-docs.
In swagger-ui.html I see only groups of endpoints but I am unable to extend any list.



In chrome debug I see:




Failed to load resource: the server responded with a status of 401 ()



Uncaught TypeError: Cannot read property 'indexOf' of undefined




and on a terminal with a server:




ERROR 10020 --- [nio-5001-exec-3] c.t.r.a.p.JwtAuthenticationEntryPoint : Responding with unauthorized error. Message - Full authentication is required to access this resource




It looks like my config files are missing something, I tried few solutions I found on a web but still nothing work.



This is my code:



pom



<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>


controller



@RestController
@PreAuthorize("hasRole('USER')")
@RequestMapping(path = "restaurant")
@Api(value="restaurant", description="Example operations for restaurants")
public class RestaurantController {
// endpoints
}


swagger bean



@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.tablebooker.restaurantservice.restaurant"))
.paths(PathSelectors.any())
.build();
}
}


SecurityConfig



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//other methods

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers("/api/auth/**")
.permitAll()
.antMatchers("/restaurant/**")
.hasRole("USER")
.anyRequest()
.authenticated();

http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

}

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**");
}
}


Any ideas how can I make my configuration work?










share|improve this question


























    up vote
    0
    down vote

    favorite












    I have a simple REST application with authentication service. I tried to add swagger and swagger-ui to it, but I can only see my endpoints in /v2/api-docs.
    In swagger-ui.html I see only groups of endpoints but I am unable to extend any list.



    In chrome debug I see:




    Failed to load resource: the server responded with a status of 401 ()



    Uncaught TypeError: Cannot read property 'indexOf' of undefined




    and on a terminal with a server:




    ERROR 10020 --- [nio-5001-exec-3] c.t.r.a.p.JwtAuthenticationEntryPoint : Responding with unauthorized error. Message - Full authentication is required to access this resource




    It looks like my config files are missing something, I tried few solutions I found on a web but still nothing work.



    This is my code:



    pom



    <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
    </dependency>
    <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
    </dependency>


    controller



    @RestController
    @PreAuthorize("hasRole('USER')")
    @RequestMapping(path = "restaurant")
    @Api(value="restaurant", description="Example operations for restaurants")
    public class RestaurantController {
    // endpoints
    }


    swagger bean



    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
    @Bean
    public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
    .select()
    .apis(RequestHandlerSelectors.basePackage("com.tablebooker.restaurantservice.restaurant"))
    .paths(PathSelectors.any())
    .build();
    }
    }


    SecurityConfig



    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(
    securedEnabled = true,
    jsr250Enabled = true,
    prePostEnabled = true
    )
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //other methods

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http
    .cors()
    .and()
    .csrf()
    .disable()
    .exceptionHandling()
    .authenticationEntryPoint(unauthorizedHandler)
    .and()
    .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
    .authorizeRequests()
    .antMatchers("/",
    "/favicon.ico",
    "/**/*.png",
    "/**/*.gif",
    "/**/*.svg",
    "/**/*.jpg",
    "/**/*.html",
    "/**/*.css",
    "/**/*.js")
    .permitAll()
    .antMatchers("/api/auth/**")
    .permitAll()
    .antMatchers("/restaurant/**")
    .hasRole("USER")
    .anyRequest()
    .authenticated();

    http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**");
    }
    }


    Any ideas how can I make my configuration work?










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I have a simple REST application with authentication service. I tried to add swagger and swagger-ui to it, but I can only see my endpoints in /v2/api-docs.
      In swagger-ui.html I see only groups of endpoints but I am unable to extend any list.



      In chrome debug I see:




      Failed to load resource: the server responded with a status of 401 ()



      Uncaught TypeError: Cannot read property 'indexOf' of undefined




      and on a terminal with a server:




      ERROR 10020 --- [nio-5001-exec-3] c.t.r.a.p.JwtAuthenticationEntryPoint : Responding with unauthorized error. Message - Full authentication is required to access this resource




      It looks like my config files are missing something, I tried few solutions I found on a web but still nothing work.



      This is my code:



      pom



      <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.9.2</version>
      </dependency>
      <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.9.2</version>
      </dependency>


      controller



      @RestController
      @PreAuthorize("hasRole('USER')")
      @RequestMapping(path = "restaurant")
      @Api(value="restaurant", description="Example operations for restaurants")
      public class RestaurantController {
      // endpoints
      }


      swagger bean



      @Configuration
      @EnableSwagger2
      public class SwaggerConfig {
      @Bean
      public Docket api() {
      return new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.basePackage("com.tablebooker.restaurantservice.restaurant"))
      .paths(PathSelectors.any())
      .build();
      }
      }


      SecurityConfig



      @Configuration
      @EnableWebSecurity
      @EnableGlobalMethodSecurity(
      securedEnabled = true,
      jsr250Enabled = true,
      prePostEnabled = true
      )
      public class SecurityConfig extends WebSecurityConfigurerAdapter {
      //other methods

      @Override
      protected void configure(HttpSecurity http) throws Exception {
      http
      .cors()
      .and()
      .csrf()
      .disable()
      .exceptionHandling()
      .authenticationEntryPoint(unauthorizedHandler)
      .and()
      .sessionManagement()
      .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
      .and()
      .authorizeRequests()
      .antMatchers("/",
      "/favicon.ico",
      "/**/*.png",
      "/**/*.gif",
      "/**/*.svg",
      "/**/*.jpg",
      "/**/*.html",
      "/**/*.css",
      "/**/*.js")
      .permitAll()
      .antMatchers("/api/auth/**")
      .permitAll()
      .antMatchers("/restaurant/**")
      .hasRole("USER")
      .anyRequest()
      .authenticated();

      http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

      }

      @Override
      public void configure(WebSecurity web) throws Exception {
      web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**");
      }
      }


      Any ideas how can I make my configuration work?










      share|improve this question













      I have a simple REST application with authentication service. I tried to add swagger and swagger-ui to it, but I can only see my endpoints in /v2/api-docs.
      In swagger-ui.html I see only groups of endpoints but I am unable to extend any list.



      In chrome debug I see:




      Failed to load resource: the server responded with a status of 401 ()



      Uncaught TypeError: Cannot read property 'indexOf' of undefined




      and on a terminal with a server:




      ERROR 10020 --- [nio-5001-exec-3] c.t.r.a.p.JwtAuthenticationEntryPoint : Responding with unauthorized error. Message - Full authentication is required to access this resource




      It looks like my config files are missing something, I tried few solutions I found on a web but still nothing work.



      This is my code:



      pom



      <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.9.2</version>
      </dependency>
      <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.9.2</version>
      </dependency>


      controller



      @RestController
      @PreAuthorize("hasRole('USER')")
      @RequestMapping(path = "restaurant")
      @Api(value="restaurant", description="Example operations for restaurants")
      public class RestaurantController {
      // endpoints
      }


      swagger bean



      @Configuration
      @EnableSwagger2
      public class SwaggerConfig {
      @Bean
      public Docket api() {
      return new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.basePackage("com.tablebooker.restaurantservice.restaurant"))
      .paths(PathSelectors.any())
      .build();
      }
      }


      SecurityConfig



      @Configuration
      @EnableWebSecurity
      @EnableGlobalMethodSecurity(
      securedEnabled = true,
      jsr250Enabled = true,
      prePostEnabled = true
      )
      public class SecurityConfig extends WebSecurityConfigurerAdapter {
      //other methods

      @Override
      protected void configure(HttpSecurity http) throws Exception {
      http
      .cors()
      .and()
      .csrf()
      .disable()
      .exceptionHandling()
      .authenticationEntryPoint(unauthorizedHandler)
      .and()
      .sessionManagement()
      .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
      .and()
      .authorizeRequests()
      .antMatchers("/",
      "/favicon.ico",
      "/**/*.png",
      "/**/*.gif",
      "/**/*.svg",
      "/**/*.jpg",
      "/**/*.html",
      "/**/*.css",
      "/**/*.js")
      .permitAll()
      .antMatchers("/api/auth/**")
      .permitAll()
      .antMatchers("/restaurant/**")
      .hasRole("USER")
      .anyRequest()
      .authenticated();

      http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

      }

      @Override
      public void configure(WebSecurity web) throws Exception {
      web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**");
      }
      }


      Any ideas how can I make my configuration work?







      java spring spring-security swagger swagger-ui






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 19 at 20:10









      Rafalsky

      55




      55
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          First you should registry swagger's resources.



          @Configuration
          public class WebMvcConfig extends WebMvcConfigurerAdapter {


          @Override
          public void addResourceHandlers(ResourceHandlerRegistry registry) {
          registry.addResourceHandler("swagger-ui.html")
          .addResourceLocations("classpath:/META-INF/resources/");
          }
          }


          Then cause you're using Spring Security,maybe you should shutdown privileges.



             @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring().mvcMatchers(HttpMethod.OPTIONS, "/**");
          // ignore swagger
          web.ignoring().mvcMatchers("/swagger-ui.html/**", "/configuration/**", "/swagger-resources/**", "/v2/api-docs");
          }


          And maybe it's better for you to use swagger which the version is under 2.8.0,or you may have to face to lots of bugs.






          share|improve this answer























          • I just downgrade version and it works. Do the rest of the steps is mandatory? Thanks a lot for help :)
            – Rafalsky
            Nov 20 at 20:07










          • If you have already done those,then there is no need to do that again.It's just a checking process.
            – AokoQin
            Nov 21 at 2:07













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53381926%2fswagger-ui-with-spring-security%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote



          accepted










          First you should registry swagger's resources.



          @Configuration
          public class WebMvcConfig extends WebMvcConfigurerAdapter {


          @Override
          public void addResourceHandlers(ResourceHandlerRegistry registry) {
          registry.addResourceHandler("swagger-ui.html")
          .addResourceLocations("classpath:/META-INF/resources/");
          }
          }


          Then cause you're using Spring Security,maybe you should shutdown privileges.



             @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring().mvcMatchers(HttpMethod.OPTIONS, "/**");
          // ignore swagger
          web.ignoring().mvcMatchers("/swagger-ui.html/**", "/configuration/**", "/swagger-resources/**", "/v2/api-docs");
          }


          And maybe it's better for you to use swagger which the version is under 2.8.0,or you may have to face to lots of bugs.






          share|improve this answer























          • I just downgrade version and it works. Do the rest of the steps is mandatory? Thanks a lot for help :)
            – Rafalsky
            Nov 20 at 20:07










          • If you have already done those,then there is no need to do that again.It's just a checking process.
            – AokoQin
            Nov 21 at 2:07

















          up vote
          0
          down vote



          accepted










          First you should registry swagger's resources.



          @Configuration
          public class WebMvcConfig extends WebMvcConfigurerAdapter {


          @Override
          public void addResourceHandlers(ResourceHandlerRegistry registry) {
          registry.addResourceHandler("swagger-ui.html")
          .addResourceLocations("classpath:/META-INF/resources/");
          }
          }


          Then cause you're using Spring Security,maybe you should shutdown privileges.



             @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring().mvcMatchers(HttpMethod.OPTIONS, "/**");
          // ignore swagger
          web.ignoring().mvcMatchers("/swagger-ui.html/**", "/configuration/**", "/swagger-resources/**", "/v2/api-docs");
          }


          And maybe it's better for you to use swagger which the version is under 2.8.0,or you may have to face to lots of bugs.






          share|improve this answer























          • I just downgrade version and it works. Do the rest of the steps is mandatory? Thanks a lot for help :)
            – Rafalsky
            Nov 20 at 20:07










          • If you have already done those,then there is no need to do that again.It's just a checking process.
            – AokoQin
            Nov 21 at 2:07















          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          First you should registry swagger's resources.



          @Configuration
          public class WebMvcConfig extends WebMvcConfigurerAdapter {


          @Override
          public void addResourceHandlers(ResourceHandlerRegistry registry) {
          registry.addResourceHandler("swagger-ui.html")
          .addResourceLocations("classpath:/META-INF/resources/");
          }
          }


          Then cause you're using Spring Security,maybe you should shutdown privileges.



             @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring().mvcMatchers(HttpMethod.OPTIONS, "/**");
          // ignore swagger
          web.ignoring().mvcMatchers("/swagger-ui.html/**", "/configuration/**", "/swagger-resources/**", "/v2/api-docs");
          }


          And maybe it's better for you to use swagger which the version is under 2.8.0,or you may have to face to lots of bugs.






          share|improve this answer














          First you should registry swagger's resources.



          @Configuration
          public class WebMvcConfig extends WebMvcConfigurerAdapter {


          @Override
          public void addResourceHandlers(ResourceHandlerRegistry registry) {
          registry.addResourceHandler("swagger-ui.html")
          .addResourceLocations("classpath:/META-INF/resources/");
          }
          }


          Then cause you're using Spring Security,maybe you should shutdown privileges.



             @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring().mvcMatchers(HttpMethod.OPTIONS, "/**");
          // ignore swagger
          web.ignoring().mvcMatchers("/swagger-ui.html/**", "/configuration/**", "/swagger-resources/**", "/v2/api-docs");
          }


          And maybe it's better for you to use swagger which the version is under 2.8.0,or you may have to face to lots of bugs.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 20 at 6:10

























          answered Nov 20 at 2:41









          AokoQin

          794




          794












          • I just downgrade version and it works. Do the rest of the steps is mandatory? Thanks a lot for help :)
            – Rafalsky
            Nov 20 at 20:07










          • If you have already done those,then there is no need to do that again.It's just a checking process.
            – AokoQin
            Nov 21 at 2:07




















          • I just downgrade version and it works. Do the rest of the steps is mandatory? Thanks a lot for help :)
            – Rafalsky
            Nov 20 at 20:07










          • If you have already done those,then there is no need to do that again.It's just a checking process.
            – AokoQin
            Nov 21 at 2:07


















          I just downgrade version and it works. Do the rest of the steps is mandatory? Thanks a lot for help :)
          – Rafalsky
          Nov 20 at 20:07




          I just downgrade version and it works. Do the rest of the steps is mandatory? Thanks a lot for help :)
          – Rafalsky
          Nov 20 at 20:07












          If you have already done those,then there is no need to do that again.It's just a checking process.
          – AokoQin
          Nov 21 at 2:07






          If you have already done those,then there is no need to do that again.It's just a checking process.
          – AokoQin
          Nov 21 at 2:07




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53381926%2fswagger-ui-with-spring-security%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Feedback on college project

          Futebolista

          Albești (Vaslui)