简体   繁体   中英

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

I need to secure some end-point with google oauth2 and secure some end-point with api key.

Before I add ApiKeyFilter to AuthConfig, it works as expected. However, when I add the filter, I found the "/secured-with-api-key/**" and "/non-secured/**" works as expected, but the "/secured/**" can be accessed even without the jwt token.

This is the 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;
    }

This is the 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;
    }
}

This is the 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();
    }
}

Thanks in advance.

I expected "/secured/**" need jwt to access, "/secured-with-api-key/**" need a api key to access and "/non-secured/**" can access for anyone.

Use two SecurityFilterChain @Beans: one with resource-server configuration (OAuth2, secured with Bearer access-tokens) and an other one for API key. Don't forget to order the two and limit the first loaded one with securityMatcher .

For instance, with filter-chain dedicated to API-key (all routes starting with /secured-with-api-key/ ) and a default one secured with OAuth2 (all routes which didn't match previous filter-chains):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM