首页 > 解决方案 > 在带有 Spring Boot 的 Swagger 安全方案上使用两个 API 密钥

问题描述

是否可以在 Swagger 上拥有两个 API 密钥并在我的 API 中赋予它们不同的权限?

例如:

API_KEY_1 : Has access to one Post method
API_KEY_2 : Has access to all of my API

非常感谢

标签: spring-bootspring-securityswagger

解决方案


就 Spring Security 而言,这完全取决于您如何验证应用程序中的 API 密钥。一旦您设置了应用程序以验证 API 密钥并创建一个SecurityContext,您最好的选择是映射到两个不同角色之一,一个用于受限访问,一个用于所有访问。例如:

    @Configuration
    public static class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    // ...
                    .authorizeRequests()
                            .mvcMatchers(HttpMethod.POST, "/some/api").hasAnyRole("BASIC", "ADMIN")
                            .anyRequest().hasRole("ADMIN");
        }

    }

更多信息和授权示例可以在文档中找到。


推荐阅读