Swagger 3.0 (OAS) With Spring Boot and Azure AD

Pradeep Maiya
Version 1
Published in
5 min readMar 31, 2023
Swagger 3.0 (OpenAPI Specification) + Spring Boot integration

This blog will discuss how to configure Swagger UI to include a Token-based authorization when it calls our API.

Points to be covered in this documentation:

  1. Introduction
  2. What is meant by Swagger documentation?
  3. Advantages of using Swagger
  4. How to achieve it in Spring Boot
  5. Conclusion

Introduction

In the REST API world, whatever APIs are designed should be documented in a good format so that it would be helpful to quickly understand what this API is for and its use cases. Creating API documentation manually is a time-consuming and tedious process. Swagger provides an option to generate the API documentation automatically and it also ensures that any changes to the API are available to the customer immediately. In this document, we will learn to integrate Swagger with the Spring Boot application along with Azure AD security.

What is meant by Swagger documentation?

Swagger provides you with a platform to create more meaningful descriptions of your APIs, an easy-to-use suite of API development tools for developers, enabling development across the entire API life cycle, which includes design, documentation, testing, and deployment. It provides data in JSON format and a UI using the Swagger-UI. In this post, we will use Springfox.

Springfox is a Java library that is used to generate API specifications for Spring Boot projects. It will examine an application once at runtime to fetch API semantics based on Spring annotations that were used in the project class structure.

Advantages of using Swagger

Adding Swagger documentation will provide lots of advantages as well, these are a few:

  1. Swagger allows us to generate REST API documentation and provides a platform to interact with those listed APIs as well.
  2. Swagger is not language specific, meaning it can be across languages like Java, .Net, HTML5, etc.
  3. This will act as a contract document that can be used to fasten the software development process.
  4. Since Swagger UI provides Interface for documenting & testing API endpoints, this will be an added advantage for using Swagger documentation.

How to achieve it in Spring Boot

The initial step will help you to configure the Azure AD Authentication mechanism to your Spring Boot application. If you haven’t configured it already, here is documentation that will provide you with the detailed steps for achieving the same.

Once you configured Azure AD with your project as shown in the above documentation, following the below steps will explain how to set up a configuration class for Swagger and to make sure all the API endpoints present in the project are secured, whenever anyone tries to hit API endpoints through swagger.

Assuming you are done with Azure AD integration of your project, now let us look at how to access secured/Authenticated API endpoints from Swagger UI and integration of Swagger UI with your project/solution.

Follow the below steps:

  1. Adding “springfox” dependency under pom.xml file:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>

Once the above dependency has been added under “pom.xml”, then it’s time to configure our Swagger Configuration class.

2. Create a new class called “SwaggerConfig” under the “Configuration” package present in your “src” package. File contents are as shown below:

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer{

public static final String AUTHORIZATION_HEADER = "Authorization";

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("PROJECT_NAME")
.version("1.0.0")
.description("THIS_WILL_PROVIDE_BRIEF_DESCRIPTION_ABOUT_YOUR_PROJECT.")
.termsOfServiceUrl("https://PROJECT_TERMS_AND_CONDITION_PAGE/")
.build();
}

@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.useDefaultResponseMessages(false)
.securityContexts(Arrays.asList(securityContext()))
.securitySchemes(Arrays.asList(apiKey()))
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();

}

private ApiKey apiKey() {
return new ApiKey(AUTHORIZATION_HEADER, "JWT", "header");
}

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

List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Arrays.asList(new SecurityReference(AUTHORIZATION_HEADER, authorizationScopes));
}

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

@Bean
public InternalResourceViewResolver defaultViewResolver() {
return new InternalResourceViewResolver();
}

Now let’s analyse the above code added:

1. @EnableSwagger2 annotation enables swagger 2 in our project.

2. Method apiInfo() is to add brief information about the project, which will be shown on Swagger documentation.

3. Method api() is used to add security context, project information written in apiInfo(), PathSelectors.any() ensure that all the API documentation is available.

4. Method apiKey() is to include a Token generated as a successful Azure AD authentication as an authorization header.

5. Method securityContext() is to configure & build Token SecurityContext with a global levelAuthorizationScope.

6. Method defaultAuth() is to set to setup AuthoizationScopes which were used in securityContext() for building the context.

7. Once we have all the above methods in place, we need to make sure to overwrite the existing resource handler to make sure Swagger URLs are added properly under META-INF/resources/ folder, and logic has been implemented under the addResourceHandlers() method.

Once we successfully added SwaggerConfiguration class as discussed above, one last thing that we need to make sure to add is to allow in security level.

3. Allow Security Level for Swagger APIs

Now we need to extend WebSecurityConfigurerAdapter which defines rules to specify what URIs to protect or pass through. This provides us with a configuration method. Add the below method in your “SecurityConfig” class where we configure Azure AD security for the project.

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

That’s pretty much it for adding Swagger 3.0 to your application. Run your application and navigate to http://localhost:8080/swagger-ui/# in the browser. Swagger UI will be seen below.

Home page of Swagger documentation

Now when you click on the Authorize button, Swagger UI will ask for the Token. Then we need to input our token along with the “Bearer” string and click on Authorize, as shown below:

Authorize section where we need to add Token generated from successful ADlogin

This above step makes sure all the requests made to our API will automatically contain the token in the HTTP headers.

4. API Request through Swagger using Token:

Below is an example of a successful response(HTTP Status code- 200) from the authorized API endpoints.

After successfully Authorizing in the above step, 200 responses for the API call

If the Token is not added/invalid under the “Authorize” section, you will get an unauthorized response with HTTP Status code- 401.

Below is an example of an unsuccessful API request with the response(HTTP Status code- 401) from API endpoints.

Unauthorized error for invalid/no token being added

Conclusion

In this document, we get to know how to set up Swagger 3.0 with Spring Boot along with Azure AD security in place, which can be helpful when dealing with our application authorization. After authorizing in Swagger UI, all the requests will automatically include our Token based Authorization.

About the author

Pradeep Maiya is a Java Developer at Version 1.

--

--