How to implement the basic Authentication for Swagger Dependency in spring boot? I have the dependencies for Swagger:
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
The SwaggerConfig class like this:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
And annotation on Controller
@ApiOperation(value = "auth",authorizations = { @Authorization(value="basicAuth") })
public class CarController {
But still my endpoints are unauthorized
I tried many suggestions, but no success! Can anyone help me in this case?
CodePudding user response:
Create a configuration class to configure basic authentication:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/swagger-ui.html", "/v2/api-docs").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
Add the Authorization annotation to your API operation with a value of "basicAuth":
@ApiOperation(value = "auth",authorizations = { @Authorization(value="basicAuth") })
public class CarController {
// ...
}
Ensure that you have a user account set up in your application to access the API endpoints. You can set up a user account in your application.yml file:
spring:
security:
user:
name: admin
password: admin
The code provided above is just a sample to give you an idea of how to implement basic authentication for Swagger in Spring Boot.