java 有没有一种方法可以在Sping Boot 中为某个端点使用API密钥,并为另一个端点使用OAuth2?[副本]

uqdfh47h  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(110)

此问题已在此处有答案

Spring Security : Multiple HTTP Config not working(2个答案)
9小时前关闭
我需要使用Google OAuth2保护一些端点,并使用API密钥保护一些其他端点。
在我将ApiKeyFilter添加到AuthConfig之前,它按预期工作。然而,当我添加过滤器时,我发现"/secured-with-api-key/**""/non-secured/**"可以正常工作,但是"/secured/**"即使没有JWT令牌也可以访问。
这是ApiKeyAuthFilter:

public class ApiKeyAuthFilter extends AbstractPreAuthenticatedProcessingFilter {
private static final Logger LOG = LoggerFactory.getLogger(ApiKeyAuthFilter.class);

    private final String apiKeyHeaderName;
    private final String timestampHeaderName;
    private final String signatureHeaderName;
    
    public ApiKeyAuthFilter(String apiKeyHeaderName, String timestampHeaderName, String signatureHeaderName) {
        this.apiKeyHeaderName = apiKeyHeaderName;
        this.timestampHeaderName = timestampHeaderName;
        this.signatureHeaderName = signatureHeaderName;
    }
    
    @Override
    protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
        String apiKey = request.getHeader(apiKeyHeaderName);
        String timestamp = request.getHeader(timestampHeaderName);
        String signature = request.getHeader(signatureHeaderName);
        return new AuthPrincipal(apiKey, timestamp, signature);
    }
    
    @Override
    protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
        // No creds when using API key
        return null;
    }

这是SimpleAuthenticationManager:

@Component
public class SimpleAuthenticationManager implements AuthenticationManager {

    private static final Logger LOG = LoggerFactory.getLogger(SimpleAuthenticationManager.class);

    @Autowired
    private ApiKeysDatabase apiKeysDatabase;

    @Autowired
    private TokenVerifier tokenVerifier;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        AuthPrincipal principal = (AuthPrincipal) authentication.getPrincipal();
        if (principal.getApikey() == null || principal.getTimestamp() == null || principal.getSignature() == null) {
            throw new BadCredentialsException("The API_KEY/timestamp/signature Header is missing.");
        }
        if (!apiKeysDatabase.isValidKey(principal.getApikey())) {
            throw new BadCredentialsException("The API key was not found or not the expected value.");
        }
        if (!tokenVerifier.isTokenAuthorized(principal)) {
            throw new BadCredentialsException("The signature is invalid");
        }
        authentication.setAuthenticated(true);
        return authentication;
    }
}

这是AuthConfig:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AuthConfig extends WebSecurityConfigurerAdapter {

    private static final String API_KEY_HEADER_NAME = "API_KEY";
    private static final String TIMESTAMP_HEADER_NAME = "timestamp";
    private static final String SIGNATURE_HEADER_NAME = "signature";

    @Autowired
    private SimpleAuthenticationManager simpleAuthenticationManager;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ApiKeyAuthFilter filter = new ApiKeyAuthFilter(API_KEY_HEADER_NAME, TIMESTAMP_HEADER_NAME, SIGNATURE_HEADER_NAME);
        filter.setAuthenticationManager(simpleAuthenticationManager);

        http.antMatcher("/secured/**")
                .authorizeRequests()
                .antMatchers("/secured/**")
                .fullyAuthenticated();

        http.antMatcher("/non-secured/**")
                .authorizeRequests()
                .antMatchers("/non-secured/**")
                .permitAll();

        http.antMatcher("/secured-with-api-key/**")
                .addFilter(filter)
                .authorizeRequests()
                .antMatchers("/secured-with-api-key/**")
                .authenticated();

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.cors().and().csrf().disable();

        http.oauth2ResourceServer().jwt();
    }
}

我预计"/secured/**"需要JWT来访问,"/secured-with-api-key/**"需要API密钥来访问,而"/non-secured/**"可以被任何人访问。

5tmbdcev

5tmbdcev1#

使用两个SecurityFilterChain@Beans:一个具有资源服务器配置(OAuth2,用承载访问令牌保护),另一个用于API密钥。不要忘记订购两个,并限制第一个加载的securityMatcher
例如,使用专用于API密钥的过滤器链(所有路由都以/secured-with-api-key/开头)和使用OAuth2保护的默认路由(所有路由都不匹配以前的过滤器链):

@Order(Ordered.HIGHEST_PRECEDENCE)
    @Bean
    SecurityFilterChain apiKeyFilterChain(HttpSecurity http) {
        http.securityMatcher(new AntPathRequestMatcher("/secured-with-api-key/**"));
        // more API key security conf
        return http.build();
    }

    @Bean
    SecurityFilterChain defaultFilterChain(HttpSecurity http) {
        http.oauth2ResourceServer().jwt();
        // resource-server security conf
        return http.build();
    }

相关问题