簡體   English   中英

有沒有辦法在 Spring Boot 中將 api 密鑰用於某些端點並將 oauth2 用於其他端點?

[英]Is there a way to use api key for some end point and use oauth2 for other endpoint in Spring Boot?

我需要使用 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;
    }
}

這是授權配置:

@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/**"可以為任何人訪問。

使用兩個SecurityFilterChain @Beans:一個具有資源服務器配置(OAuth2,使用 Bearer 訪問令牌保護),另一個用於 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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM