Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Spring Security for OPTIONS Http Method

Is it possible to disable Spring Security for a type of HTTP Method?

We have a Spring REST application with services that require Authorization token to be attached in the header of http request. I am writing a JS client for it and using JQuery to send the GET/POST requests. The application is CORS enabled with this filter code.

doFilter(....) {    HttpServletResponse httpResp = (HttpServletResponse) response;   httpResp.setHeader("Access-Control-Allow-Origin", "*");   httpResp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");   httpResp.setHeader("Access-Control-Max-Age", "3600");   Enumeration<String> headersEnum = ((HttpServletRequest) request).getHeaders("Access-Control-Request-Headers");   StringBuilder headers = new StringBuilder();   String delim = "";   while (headersEnum.hasMoreElements()) {     headers.append(delim).append(headersEnum.nextElement());     delim = ", ";   }   httpResp.setHeader("Access-Control-Allow-Headers", headers.toString()); } 

But when JQuery sends in the OPTIONS request for CORS, the server responds with Authorization Failed token. Clearly the OPTIONS request, lacks Authorization token. So is it possible to let the OPTIONS escape the Security Layer from the Spring Security Configuration?

like image 275
Dhanush Gopinath Avatar asked Feb 11 '14 08:02

Dhanush Gopinath


People also ask

How do I disable security in Spring security?

enabled=false and management. security. enabled=false should be set to disable the security.

How do I disable Spring boot security configuration?

In Spring Boot 2, if we want our own security configuration, we can simply add a custom WebSecurityConfigurerAdapter. This will disable the default auto-configuration and enable our custom security configuration.


2 Answers

If you're using an annotation based security config file (@EnableWebSecurity & @Configuration) you can do something like the following in the configure() method to allow for the OPTION requests to be permitted by Spring Security without authentication for a given path:

@Override protected void configure(HttpSecurity http) throws Exception {      http     .csrf().disable()     .authorizeRequests()       .antMatchers(HttpMethod.OPTIONS,"/path/to/allow").permitAll()//allow CORS option calls       .antMatchers("/resources/**").permitAll()       .anyRequest().authenticated()     .and()     .formLogin()     .and()     .httpBasic(); } 
like image 121
Felby Avatar answered Sep 26 '22 14:09

Felby


Allow all OPTIONS in context:

    @Override     public void configure(WebSecurity web) throws Exception {         web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");     } 
like image 25
Luc S. Avatar answered Sep 24 '22 14:09

Luc S.