Home > database >  Spring Security header are not reflecting in API response
Spring Security header are not reflecting in API response

Time:03-08

package com.example.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .headers()
                .referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN).and()

                .frameOptions().sameOrigin().and()

                .headers().defaultsDisabled()
                .contentTypeOptions().and()

                .httpStrictTransportSecurity()
                .includeSubDomains(true)
                .maxAgeInSeconds(31536000);
    }
}

I have added this class but still i am not getting any given above headers in API response. I also tried by adding @EnableWebSecurity on class where all the APIs are mentioned. Given Below is the image of headers in response. Please check.

enter image description here

CodePudding user response:

The possible reasons could be for the reported case are

  • Spring security might be not coming in the picture. Make sure you're checking against accurate pattern (api protected by spring security)

  • Web server is filtering the set headers. As you're using Nginx so you should check for any misconfigurations on the server.

Also, Strict-Transport-Security is only added on HTTPS requests, so the following will be only relevant on https.

.httpStrictTransportSecurity()
.maxAgeInSeconds(31536000)
.includeSubDomains(true); 
  • Related