Я хотел бы защитить Spring API с помощью общего секрета.Я пытаюсь с этим кодом, однако я все еще могу получить доступ к API с помощью простого curl -X GET --header 'Accept: application / json' 'https://localhost:8443/api/status'
@Configuration
@EnableWebSecurity
@Order(1)
@PropertySource(value = {"classpath:application.properties"}, ignoreResourceNotFound = true)
public class APISecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${header-name:}")
private String principalRequestHeader;
@Value("${token}")
private String principalRequestValue;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
APIKeyAuthFilter filter = new APIKeyAuthFilter(principalRequestHeader);
filter.setAuthenticationManager(authentication -> {
String principal = (String) authentication.getPrincipal();
if (!principalRequestValue.equals(principal))
{
authentication.setAuthenticated(false);
throw new BadCredentialsException("The API key was not found or not the expected value.");
}
authentication.setAuthenticated(true);
return authentication;
});
httpSecurity.
antMatcher("/").
csrf().disable().
sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
and().addFilter(filter).authorizeRequests().anyRequest().authenticated();
}
и этот код:
public class APIKeyAuthFilter extends AbstractPreAuthenticatedProcessingFilter {
public String principalRequestHeader;
public APIKeyAuthFilter(String principalRequestHeader) {
this.principalRequestHeader = principalRequestHeader;
}
@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest httpServletRequest) {
return httpServletRequest.getHeader(principalRequestHeader);
}
@Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest httpServletRequest) {
return "N/A";
}
}
Любая помощь приветствуется