带有共享秘密的Spring MVC

时间:2018-11-26 14:30:25

标签: java spring api spring-mvc spring-security

我想使用共享密钥保护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";
}

}

任何帮助都很重要

0 个答案:

没有答案