Skip to content

How to configure HTTP Basic authentication for Swagger 2 and Spring 2

This post will explain how to configure Spring Boot 2 to access Swagger 2 using HTTP Basic authorization.


Spring Boot 2.0.4.RELEASE
Swagger 2.9.2

Create the REST controller

import com.server.common.model.Menu;
import com.server.dataservice.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

public class MenuController
    private MenuService menuService;

    public ResponseEntity<List<Menu>> getMenus() {
        return new ResponseEntity<>(menuService.getAll(), HttpStatus.OK);

Create the configuration class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

public class WebSecurityConfig extends WebSecurityConfigurerAdapter
    private AuthenticationEntryPoint authEntryPoint;

    protected void configure(HttpSecurity http) throws Exception {

    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {


You could replace the simple in-memory authentication with anything else.

Now, start your Spring Boot 2 application and navigate to http://localhost:9030/swagger-ui.html. The port may differ.

You should be presented with a login dialog. Enter the username and password from the configuration file to gain access to the Swagger UI. Or alternatively use Postman.

Notice the Authorization header! The value starts with “Basic ” followed by username:password Base64 encoded.

Published inGuideJavaProgrammingSpring Boot

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *