使用 Swagger UI 的基本身份验证 [英] Basic Authentication using Swagger UI

查看:170
本文介绍了使用 Swagger UI 的基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 Swagger UI 使用 API 文档开发基于 spring-boot 的 rest API 服务.我想通过 swagger UI 启用基本身份验证,以便用户只能在他/她使用 swagger UI 上的授权按钮进行身份验证后才能运行 API(添加了 "authorization: Basic XYZ 标头到 API 调用

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

在前端(在 Swagger UI 的 .json 文件中,我使用以下代码为所有 API 添加了基本身份验证(根据文档):

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": []
        }
    ]

我应该如何为上述用例实现后端逻辑(用户只能在使用 swagger UI 上的授权按钮进行身份验证后才能运行 API,否则在运行 API 时会显示 401 错误)

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. 当您为 Spring Boot 应用启用基本身份验证时,swagger ui 将自动使用浏览器的弹出窗口以将其用于基本身份验证.这意味着浏览器将保留用于发出请求的凭据,就像您尝试访问安全的 GET 端点一样,直到您关闭它.

现在,假设您不想使用上述内容,并希望 swagger-ui 用于基本身份验证,正如您所说,您必须在 swagger-ui 上启用身份验证功能并可选择添加安全例外访问 swagger-ui 网址时.

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. 要启用基本身份验证功能以 swagger UI (使用 UI 中的授权按钮")您必须为 Swagger Docket 设置安全上下文和方案(这是一个简化版本):

  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]);
    }

}

这将启用 ui 中的授权按钮.

This enables the authorization button in ui.

现在您可能希望您的用户自由访问 swagger-ui 并使用此按钮进行授权.为此,您必须为应用程序的基本身份验证免除 swagger.此配置的一部分是安全配置,您必须添加以下代码:

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();

    }
}

这篇关于使用 Swagger UI 的基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆