How to use spring security to prevent xss and xframe attack - spring-mvc

I look spring web site and want to prevent my website form xss and xframe attack
But My english is not well enough to figure out what to set
Please guide me what else should I setting??
I just add a WebSecurityConfig.java under src/com/test/web/security
Here is my code :
package com.test.web.security;
import org.springframework.context.annotation.ComponentScan;
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;
#EnableWebSecurity
#Configuration
#ComponentScan
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
// ...
.headers();
}
}

If you just specify the same code that you have above, Spring Security should automatically add all of the relevant security headers. Per the docs:
If you are using Spring Security’s Java configuration, all of the
default security headers are added by default.
Also:
As soon as you specify any headers that should be included, then only
those headers will be include
See details and code samples in this section:
http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#default-security-headers

Related

Spring boot application not able to access rest path

I am trying to set up the rules for spring boot to allow/deny access for specific paths. I looked up various examples and stack overflow question, but none was helpful. I created the configuration file as follows:
package xyz.blackmonster.window.configs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
#EnableWebSecurity
#Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${admin.console.username:admin}")
private String username;
#Value("${admin.console.password:admin}")
private String password;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(username)
.password(passwordEncoder().encode(password)).roles("ADMIN");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/assets/**", "/api/order/calculate", "/api/order/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/login.html")
.defaultSuccessUrl("/admin/orders.html")
.failureUrl("/login.html?error=true")
.and()
.logout().logoutSuccessUrl("/");
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
I can access the "/" without a problem. The page is loaded and show with the help of the MVC controller. But the paths that I defined as REST end points, I am not able to access them. I keep getting a 403 response:
{"timestamp":"2018-10-08T19:22:04.963+0000","status":403,"error":"Forbidden","message":"Forbidden","path":"/api/order/calculate"}
What is wrong with my configuration? As you can see from the class, I even went one further and specifically set the calculate end point as oppose to having the ** to include all subpaths.
If "/" is working and "/api/order/calculate" is not, it means that they have different HTTP verbs.
"/" - is a GET request
"/api/order/calculate" - is a POST request
By default, spring security will enable csrf protection (only for POST because GET is considered safe). If you are getting 403, it means that you are not sending csrf header => your access is forbidden.
You said that this is a REST endpoint, so you should disable csrf for this endpoints. To do that, please update your configuration with:
1.disable csrf in general (not recommended if you have web forms)
http.csrf()
.disable();
2.if you need to ignore csrf only for specific endpoints, you can add:
http.csrf()
.ignoringAntMatchers("/api/order/calculate")

Base class no longer working after upgrading to Spring Cloud Contract 1.2.0

I am in the process of upgrading to Spring Cloud Edgware.RELEASE, and I've got a question about how to properly set up a base class for Spring Cloud Contract tests. Following is what I have currently as a base class that works through Dalston.SR5:
import javax.servlet.Filter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc;
#RunWith(SpringRunner.class)
#ActiveProfiles("local")
#SpringBootTest(classes = {Bootstrap.class})
#DirtiesContext
public class ConsumerDrivenContractTests {
#Autowired
private WebApplicationContext applicationContext;
#Autowired
private Filter springSecurityFilterChain;
#Test
public void generateTestsFromGroovyFiles() {
}
#Before
public void setup() {
DefaultMockMvcBuilder defaultMockMvcBuilder =
MockMvcBuilders.webAppContextSetup(applicationContext).addFilter(springSecurityFilterChain);
MockMvc mockMvc = defaultMockMvcBuilder.build();
RestAssuredMockMvc.mockMvc(mockMvc);
}
}
Upon upgrading to Edgware.RELEASE, my import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc; no longer resolves, which is confusing. The Spring Cloud Contract documentation states "by default, Rest Assured 3.x is added to the classpath" (see http://cloud.spring.io/spring-cloud-static/spring-cloud-contract/1.2.0.RELEASE/single/spring-cloud-contract.html#maven-rest-assured), and the example given shows how to use Rest Assured 2.x with the <groupId>com.jayway.restassured</groupId> dependency. However, the <artifactId>spring-cloud-starter-contract-verifier</artifactId> for 1.2.0.RELEASE pulls in the <groupId>io.rest-assured</groupId> dependencies. Given the documentation, I was expecting the com.jayway... jars to be resolved.
Is my base class approach still valid upon upgrading to 1.2.0.RELEASE, and if so, do I need to explicitly add the com.jayway... dependencies to my pom.xml file? If so, it would be helpful if the documentation stated this.
By default, Rest Assured 3.x is added to the classpath. RestAssured 3.x. has imports io.restassured and they show up in your generated tests. You, in your base class have com.jayway which is RestAssured 2.x. So your generated tests require you to use io.restassured imports in your base class. So either you fix your base class to use Rest Assured 3.x or you have to provide an explicit dependency to Rest Assured 2.x. in your plugin to fix the imports in the generated tests.

Getting a popup for downloading the font file(ttf) in a spring-boot application

I'm getting a popup for downloading the fonts files(ttf) in a spring-boot application, the font file is related to bootstrap3.
I tried to add MimeTypes like this but still getting the popup for first time I open the application.
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.MimeMappings;
import org.springframework.stereotype.Component;
#Component
public class ServletCustomizer implements EmbeddedServletContainerCustomizer {
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
mappings.add("woff","application/x-font-woff");
mappings.add("eot","application/vnd.ms-fontobject");
mappings.add("ttf","application/x-font-ttf");
container.setMimeMappings(mappings);
}
}
I'm using Spring-boot 1.3.3.RELEASE+thymeleaf.
Anyone know how to resolve this issue?
I resolved the issue by adding this line to my security config
http.authorizeRequests().antMatchers("/fonts/**").permitAll();

How can I enable spring boot 1.2.5, using jersey, to print the raw http request and response to the console?

I have a spring boot 1.2.5 service that uses jersey 2. I see the requests in my own logs but I'd like to see the raw http request and response in the console as well. How can you turn on printing http traffic to the console?
import java.util.logging.Logger;
import org.glassfish.jersey.filter.LoggingFilter;
import javax.ws.rs.ApplicationPath;
import org.springframework.stereotype.Component;
#Component
#ApplicationPath("/")
public class JerseyConfiguration extends ResourceConfig {
private static final Logger log = Logger.getLogger(JerseyConfiguration.class.getName());
public JerseyConfiguration() {
...
register(new LoggingFilter(log, true));
}
}

Share cookies in Spring MVC

I have an existing web application which runs on
https://subdomain.example.com
Now I like to have additional subdomains
https://subdomain2.example.com
How can I set the following using Spring MVC so that the user will not be prompted for authentication again after being redirected from the first domain to the second domain ?
Set-Cookie: name=value; domain=example.com
Look at this controller example, but keep in mind 2 things:
putting an arbitrary fixed domain will not allow you to access the cookie when you work in your local environment if you connect to 127.0.0.1.
your cookie could be read by all the subdomain present on that host(example.com), not only by the ones you want.
Class:
package com.test.foo;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/foo")
public class FooController {
#RequestMapping("/cookie")
public String setCookie(HttpServletRequest request, HttpServletResponse response) {
String value = "value";
Cookie cookie = new Cookie("name", value);
cookie.setPath("/");//<-- important
cookie.setDomain("example.com");
response.addCookie(cookie);
return "foo/index";//your view
}
}

Resources