Basic Authentication using Swagger UI

a 夏天 提交于 2021-01-28 02:24:58

问题


I am trying to develop a spring-boot based rest API service with API documentation through Swagger UI. I want to enable basic authentication via the swagger UI so that the user can only run the API's once he/she authenticates using the Authorize button on swagger UI (by which a "authorization: Basic XYZ header is added to the API Call

At the front end (in the .json file for the Swagger UI I have added basic authentication for all the APIs using the following code (as per the documentation):

"securityDefinitions": {
        "basic_auth": {
            "type": "basic"
        }
    },
    "security": [
        {
            "basic_auth": []
        }
    ]

How should I implement the backend logic for the use case mentioned above (user can only run the API's once he/she authenticates using the Authorize button on swagger UI and it otherwise shows a 401 Error on running the API)

Some documentation or sample code for the same would be helpful


回答1:


One option is to use the browser pop up authorization.

  1. When you enable basic auth for your spring boot app, swagger ui will automatically use the browser's pop up window in order to use it for basic auth. This means that the browser will keep the credentials for making requests just like when you trying to access a secured GET endpoint until you close it.

Now, let's say you DON'T want to use the above and want swagger-ui for basic authentication as you say, you have to enable auth functionality on swagger-ui and optionally add security exception when accessing swagger-ui url.

  1. To enable the basic auth functionality to swagger UI (with the "Authorize button" in UI) you have to set security Context and Scheme to your Swagger Docket (This is a simplified version):

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig implements WebMvcConfigurer{
    
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build()
                    .securityContexts(Arrays.asList(securityContext()))
                    .securitySchemes(Arrays.asList(basicAuthScheme()));
       }
    
        private SecurityContext securityContext() {
            return SecurityContext.builder()
                    .securityReferences(Arrays.asList(basicAuthReference()))
                    .forPaths(PathSelectors.ant("/api/v1/**"))
                    .build();
        }
    
        private SecurityScheme basicAuthScheme() {
            return new BasicAuth("basicAuth");
        }
    
        private SecurityReference basicAuthReference() {
            return new SecurityReference("basicAuth", new AuthorizationScope[0]);
        }
    
    }
    

This enables the authorization button in ui.

Now you probably want for your users to access the swagger-ui freely and use this button for authorization. To do this you have to exempt swagger for app's basic auth. Part of this configuration is Security config and you have to add following code:

public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {

            http
                .httpBasic()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)   
                .and().authorizeRequests()
                .antMatchers(
                        "/", "/csrf", 
                        "/v2/api-docs", 
                        "/swagger-resources/**",
                        "/swagger-ui.html",
                        "/webjars/**"
                        ).permitAll()
                .anyRequest().authenticated();

    }
}



回答2:


Use a following dependency in build.gradle to enable a security:

"org.springframework.boot:spring-boot-starter-security"


In application.properties you can define your own username and password using:

spring.security.user.name=user
spring.security.user.password=password


来源:https://stackoverflow.com/questions/58110036/basic-authentication-using-swagger-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!