Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenAPI3 show methods based on Basic Authentication via Spring Boot

I added this dependency to my Spring Boot application

 <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-ui</artifactId>
      <version>1.4.3</version>
      <type>pom.sha512</type>
     </dependency>

I then was able to open : https://localhost:8443/v3/api-docs

The browser does ask me for my credentials, and as long as I enter the user/password right it works, but it shows me ALL the methods that are available globally. I would like only the methods the user has rights to, to show up in the api docs.

For a specific method is use this tag to authorize my call: @PreAuthorize("hasRole('USER') OR hasRole('ADMIN')")

This is my web security config class:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user").password(new BCryptPasswordEncoder().encode("blabl")).roles("USER")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("blabla")).roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }
}
like image 802
trilogy Avatar asked Oct 27 '22 19:10

trilogy


1 Answers

I doubt whether this is possible as the API documentation is generated at startup time (I think).

What you can do instead is to add documentation specifying which security credentials are needed for which API calls, I found a mention of this at https://github.com/springdoc/springdoc-openapi#adding-api-information-and-security-documentation

So if a user is able to see the API page, then it might also see the endpoints it does not have access to (such as /admin), but you could add documentation to it that the endpoint can only be accessed by admins.

like image 151
Davio Avatar answered Nov 15 '22 05:11

Davio