Spring Boot Oauth2 enable swagger UI with authentication
Purpose: In this post, we will learn how we can enable swagger with Authentication. The steps are given below.
1. Setup and Create Oauth2 Project: Visit here. Spring Boot Oauth2 Implementation using in-memory DB.
Next Step. Spring Boot Parent Dependencies.
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.6.RELEASE</version><relativePath /> <!-- lookup parent from repository --></parent>
Next Step. H2 Database Dependencies.
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency>
Next Step. Add swagger Dependencies.
<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>
Next Step. Add below line in application.properties for H2.
#server PORTserver.port=8081#H2 database configurationspring.datasource.driverClassName=org.h2.Driverspring.datasource.username=saspring.datasource.password=spring.jpa.database-platform=org.hibernate.dialect.H2Dialect#enabling the H2 consolespring.h2.console.enabled=truespring.jpa.show-sql=truespring.jpa.generate-ddl=truespring.jpa.hibernate.ddl-auto=update# Before run change directoryspring.datasource.url=jdbc:h2:C:/data/oauth2# Custom H2 Console URLspring.h2.console.path=/h2
Next Step. To enable swagger console add yellow highlighted line in SecurityConfig.java file.
package com.bce.configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@EnableWebSecurity@EnableGlobalMethodSecurity(securedEnabled = true)public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**","/swagger-ui.html", "/webjars/**");}.......}
Next Step. To enable swagger console add SwaggerConfig.java file.
package com.bce.configuration;import static com.google.common.collect.Lists.newArrayList;import java.util.Collections;import java.util.List;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.bind.annotation.RequestMethod;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo;import springfox.documentation.service.AuthorizationScope;import springfox.documentation.service.Contact;import springfox.documentation.service.GrantType;import springfox.documentation.service.OAuth;import springfox.documentation.service.ResourceOwnerPasswordCredentialsGrant;import springfox.documentation.service.ResponseMessage;import springfox.documentation.service.SecurityReference;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spi.service.contexts.SecurityContext;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger.web.ApiKeyVehicle;import springfox.documentation.swagger.web.SecurityConfiguration;import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration@EnableSwagger2public class SwaggerConfig {@Value("${authentication.oauth.clientid}")private String clientId;@Value("${authentication.oauth.secret}")private String clientSecret;@Value("${authentication.oauth.token.url}")private String authLink;@Beanpublic Docket api() {List<ResponseMessage> list = new java.util.ArrayList<>();return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build().securitySchemes(Collections.singletonList(securitySchema())).securityContexts(Collections.singletonList(securityContext())).pathMapping("/").useDefaultResponseMessages(false).apiInfo(apiInfo()).globalResponseMessage(RequestMethod.GET, list).globalResponseMessage(RequestMethod.POST, list);}private OAuth securitySchema() {List<AuthorizationScope> authorizationScopeList = newArrayList();authorizationScopeList.add(new AuthorizationScope("read", "read all"));authorizationScopeList.add(new AuthorizationScope("write", "access all"));List<GrantType> grantTypes = newArrayList();GrantType creGrant = new ResourceOwnerPasswordCredentialsGrant(authLink + "/oauth/token");grantTypes.add(creGrant);return new OAuth("oauth2schema", authorizationScopeList, grantTypes);}private SecurityContext securityContext() {return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.ant("/**")).build();}private List<SecurityReference> defaultAuth() {final AuthorizationScope[] authorizationScopes = new AuthorizationScope[3];authorizationScopes[0] = new AuthorizationScope("read", "read all");authorizationScopes[1] = new AuthorizationScope("trust", "trust all");authorizationScopes[2] = new AuthorizationScope("write", "write all");return Collections.singletonList(new SecurityReference("oauth2schema", authorizationScopes));}@SuppressWarnings("deprecation")@Beanpublic SecurityConfiguration securityInfo() {return new SecurityConfiguration(clientId, clientSecret, "", "", "", ApiKeyVehicle.HEADER, "", " ");}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("Dropu2 API").description("").termsOfServiceUrl("http://localhost:8080/api/swagger-ui.html").contact(new Contact("Narottam Singh", "", "naottammca2009@gmail.com")).version("1.0.0").build();}}
Next Step. Open swagger UI and Authenticate and test API.
No comments:
Post a Comment