Restricting requests based on origin for spring boot APIs

Viewed 247

I was wondering if there is a way to restrict access to a spring boot REST API based on the origin of the request. My requirement is to allow requests from a domain, for e.g. abc.com, but block the requests from other sources like a REST client like POSTMAN.

I have tried the following code, but it doesn't seem to work. I am able to access the API from POSTMAN, but I get a CORS error when trying to call the API from abc.com.

@Component
public class ApiCorsFilters extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "abc.com");
    }
}

@Configuration
public class WebControllerConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("abc.com");
    }
}

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").
                permitAll().and().csrf().disable();
    }
}

Is this possible to achieve this sort of access control? If yes, how effective is it?

0 Answers
Related