Skip to content

Commit 8de8770

Browse files
BogdanStoeanpivovarit
authored andcommitted
[BAEL-1410] Spring Boot Security auto-configuration (eugenp#3329)
* [BAEL-1410] Spring Boot Security Auto-Configuration * [BAEL-1410] Added some tests for incorrect credentials use case * [BAEL-1410] Added readme and some code improvements
1 parent 62e5395 commit 8de8770

10 files changed

Lines changed: 349 additions & 1 deletion

File tree

‎pom.xml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,8 @@
152152
<module>spring-boot</module>
153153
<module>spring-boot-keycloak</module>
154154
<module>spring-boot-bootstrap</module>
155+
<module>spring-boot-admin</module>
156+
<module>spring-boot-security</module>
155157
<module>spring-cloud-data-flow</module>
156158
<module>spring-cloud</module>
157159
<module>spring-core</module>
@@ -263,7 +265,6 @@
263265
<module>vertx-and-rxjava</module>
264266
<module>saas</module>
265267
<module>deeplearning4j</module>
266-
<module>spring-boot-admin</module>
267268
<module>lucene</module>
268269
<module>vraptor</module>
269270
</modules>

‎spring-boot-security/README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
### Spring Boot Security Auto-Configuration
2+
3+
- mvn clean install
4+
- uncomment in application.properties spring.profiles.active=basic # for basic auth config
5+
- uncomment in application.properties spring.profiles.active=form # for form based auth config
6+
- uncomment actuator dependency simultaneously with the line from main class

‎spring-boot-security/pom.xml‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
6+
<groupId>com.baeldung</groupId>
7+
<artifactId>spring-boot-security</artifactId>
8+
<version>0.0.1-SNAPSHOT</version>
9+
<packaging>jar</packaging>
10+
11+
<name>spring-boot-security</name>
12+
<description>Spring Boot Security Auto-Configuration</description>
13+
14+
<parent>
15+
<groupId>com.baeldung</groupId>
16+
<artifactId>parent-modules</artifactId>
17+
<version>1.0.0-SNAPSHOT</version>
18+
</parent>
19+
<dependencyManagement>
20+
<dependencies>
21+
<dependency>
22+
<groupId>org.springframework.boot</groupId>
23+
<artifactId>spring-boot-dependencies</artifactId>
24+
<version>1.5.9.RELEASE</version>
25+
<type>pom</type>
26+
<scope>import</scope>
27+
</dependency>
28+
</dependencies>
29+
</dependencyManagement>
30+
31+
<properties>
32+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
33+
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
34+
<java.version>1.8</java.version>
35+
</properties>
36+
37+
<dependencies>
38+
<!--<dependency>-->
39+
<!--<groupId>org.springframework.boot</groupId>-->
40+
<!--<artifactId>spring-boot-starter-actuator</artifactId>-->
41+
<!--</dependency>-->
42+
<dependency>
43+
<groupId>org.springframework.boot</groupId>
44+
<artifactId>spring-boot-starter-security</artifactId>
45+
</dependency>
46+
<dependency>
47+
<groupId>org.springframework.boot</groupId>
48+
<artifactId>spring-boot-starter-web</artifactId>
49+
</dependency>
50+
51+
<dependency>
52+
<groupId>org.springframework.boot</groupId>
53+
<artifactId>spring-boot-starter-test</artifactId>
54+
<scope>test</scope>
55+
</dependency>
56+
<dependency>
57+
<groupId>org.springframework.security</groupId>
58+
<artifactId>spring-security-test</artifactId>
59+
<scope>test</scope>
60+
</dependency>
61+
</dependencies>
62+
63+
<build>
64+
<plugins>
65+
<plugin>
66+
<groupId>org.springframework.boot</groupId>
67+
<artifactId>spring-boot-maven-plugin</artifactId>
68+
</plugin>
69+
</plugins>
70+
</build>
71+
72+
73+
</project>
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.baeldung.springbootsecurity;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
6+
7+
@SpringBootApplication(exclude = {
8+
SecurityAutoConfiguration.class
9+
// ,ManagementWebSecurityAutoConfiguration.class
10+
})
11+
public class SpringBootSecurityApplication {
12+
13+
public static void main(String[] args) {
14+
SpringApplication.run(SpringBootSecurityApplication.class, args);
15+
}
16+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.baeldung.springbootsecurity.config;
2+
3+
import org.springframework.context.annotation.Configuration;
4+
import org.springframework.context.annotation.Profile;
5+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
6+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
8+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
9+
10+
@Configuration
11+
@EnableWebSecurity
12+
@Profile("basic")
13+
public class BasicConfiguration extends WebSecurityConfigurerAdapter {
14+
15+
@Override
16+
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
17+
auth
18+
.inMemoryAuthentication()
19+
.withUser("user")
20+
.password("password")
21+
.roles("USER")
22+
.and()
23+
.withUser("admin")
24+
.password("admin")
25+
.roles("USER", "ADMIN");
26+
}
27+
28+
@Override
29+
protected void configure(HttpSecurity http) throws Exception {
30+
http
31+
.authorizeRequests()
32+
.anyRequest()
33+
.authenticated()
34+
.and()
35+
.httpBasic();
36+
}
37+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.baeldung.springbootsecurity.config;
2+
3+
import org.springframework.context.annotation.Configuration;
4+
import org.springframework.context.annotation.Profile;
5+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
6+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
8+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
9+
10+
@Configuration
11+
@EnableWebSecurity
12+
@Profile("form")
13+
public class FormLoginConfiguration extends WebSecurityConfigurerAdapter {
14+
15+
@Override
16+
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
17+
auth
18+
.inMemoryAuthentication()
19+
.withUser("user")
20+
.password("password")
21+
.roles("USER")
22+
.and()
23+
.withUser("admin")
24+
.password("password")
25+
.roles("USER", "ADMIN");
26+
}
27+
28+
@Override
29+
protected void configure(HttpSecurity http) throws Exception {
30+
http
31+
.authorizeRequests()
32+
.anyRequest()
33+
.authenticated()
34+
.and()
35+
.formLogin()
36+
.and()
37+
.httpBasic();
38+
}
39+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
2+
#spring.profiles.active=form
3+
#spring.profiles.active=basic
4+
#security.user.password=password
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Index</title>
6+
</head>
7+
<body>
8+
Welcome to Baeldung Secured Page !!!
9+
</body>
10+
</html>
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.baeldung.springbootsecurity;
2+
3+
import org.junit.Before;
4+
import org.junit.Test;
5+
import org.junit.runner.RunWith;
6+
import org.springframework.boot.context.embedded.LocalServerPort;
7+
import org.springframework.boot.test.context.SpringBootTest;
8+
import org.springframework.boot.test.web.client.TestRestTemplate;
9+
import org.springframework.http.HttpStatus;
10+
import org.springframework.http.ResponseEntity;
11+
import org.springframework.test.context.ActiveProfiles;
12+
import org.springframework.test.context.junit4.SpringRunner;
13+
14+
import java.io.IOException;
15+
import java.net.MalformedURLException;
16+
import java.net.URL;
17+
18+
import static org.junit.Assert.assertEquals;
19+
import static org.junit.Assert.assertTrue;
20+
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
21+
22+
@RunWith(SpringRunner.class)
23+
@SpringBootTest(webEnvironment = RANDOM_PORT)
24+
@ActiveProfiles("basic")
25+
public class BasicConfigurationIntegrationTest {
26+
27+
TestRestTemplate restTemplate;
28+
URL base;
29+
30+
@LocalServerPort int port;
31+
32+
@Before
33+
public void setUp() throws MalformedURLException {
34+
restTemplate = new TestRestTemplate("user", "password");
35+
base = new URL("http://localhost:" + port);
36+
}
37+
38+
@Test
39+
public void whenLoggedUserRequestsHomePage_ThenSuccess() throws IllegalStateException, IOException {
40+
ResponseEntity<String> response = restTemplate.getForEntity(base.toString(), String.class);
41+
assertEquals(HttpStatus.OK, response.getStatusCode());
42+
assertTrue(response
43+
.getBody()
44+
.contains("Baeldung"));
45+
}
46+
47+
@Test
48+
public void whenUserWithWrongCredentialsRequestsHomePage_ThenUnauthorizedPage() throws IllegalStateException, IOException {
49+
restTemplate = new TestRestTemplate("user", "wrongpassword");
50+
ResponseEntity<String> response = restTemplate.getForEntity(base.toString(), String.class);
51+
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
52+
assertTrue(response
53+
.getBody()
54+
.contains("Unauthorized"));
55+
}
56+
}
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
package com.baeldung.springbootsecurity;
2+
3+
import org.junit.Test;
4+
import org.junit.runner.RunWith;
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.boot.context.embedded.LocalServerPort;
7+
import org.springframework.boot.test.context.SpringBootTest;
8+
import org.springframework.boot.test.web.client.TestRestTemplate;
9+
import org.springframework.http.*;
10+
import org.springframework.test.context.ActiveProfiles;
11+
import org.springframework.test.context.junit4.SpringRunner;
12+
import org.springframework.util.LinkedMultiValueMap;
13+
import org.springframework.util.MultiValueMap;
14+
15+
import java.util.Collections;
16+
import java.util.regex.Matcher;
17+
import java.util.regex.Pattern;
18+
19+
import static org.junit.Assert.*;
20+
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
21+
22+
@RunWith(SpringRunner.class)
23+
@SpringBootTest(webEnvironment = RANDOM_PORT)
24+
@ActiveProfiles("form")
25+
public class FormConfigurationIntegrationTest {
26+
27+
@Autowired TestRestTemplate restTemplate;
28+
@LocalServerPort int port;
29+
30+
@Test
31+
public void whenLoginPageIsRequested_ThenSuccess() {
32+
HttpHeaders httpHeaders = new HttpHeaders();
33+
httpHeaders.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
34+
ResponseEntity<String> responseEntity = restTemplate.exchange("/login", HttpMethod.GET, new HttpEntity<Void>(httpHeaders), String.class);
35+
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
36+
assertTrue(responseEntity
37+
.getBody()
38+
.contains("_csrf"));
39+
}
40+
41+
@Test
42+
public void whenTryingToLoginWithCorrectCredentials_ThenAuthenticateWithSuccess() {
43+
HttpHeaders httpHeaders = getHeaders();
44+
httpHeaders.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
45+
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
46+
MultiValueMap<String, String> form = getFormSubmitCorrectCredentials();
47+
ResponseEntity<String> responseEntity = this.restTemplate.exchange("/login", HttpMethod.POST, new HttpEntity<>(form, httpHeaders), String.class);
48+
assertEquals(responseEntity.getStatusCode(), HttpStatus.FOUND);
49+
assertTrue(responseEntity
50+
.getHeaders()
51+
.getLocation()
52+
.toString()
53+
.endsWith(this.port + "/"));
54+
assertNotNull(responseEntity
55+
.getHeaders()
56+
.get("Set-Cookie"));
57+
}
58+
59+
@Test
60+
public void whenTryingToLoginWithInorrectCredentials_ThenAuthenticationFailed() {
61+
HttpHeaders httpHeaders = getHeaders();
62+
httpHeaders.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
63+
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
64+
MultiValueMap<String, String> form = getFormSubmitIncorrectCredentials();
65+
ResponseEntity<String> responseEntity = this.restTemplate.exchange("/login", HttpMethod.POST, new HttpEntity<>(form, httpHeaders), String.class);
66+
assertEquals(responseEntity.getStatusCode(), HttpStatus.FOUND);
67+
assertTrue(responseEntity
68+
.getHeaders()
69+
.getLocation()
70+
.toString()
71+
.endsWith(this.port + "/login?error"));
72+
assertNull(responseEntity
73+
.getHeaders()
74+
.get("Set-Cookie"));
75+
}
76+
77+
private MultiValueMap<String, String> getFormSubmitCorrectCredentials() {
78+
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
79+
form.set("username", "user");
80+
form.set("password", "password");
81+
return form;
82+
}
83+
84+
private MultiValueMap<String, String> getFormSubmitIncorrectCredentials() {
85+
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
86+
form.set("username", "user");
87+
form.set("password", "wrongpassword");
88+
return form;
89+
}
90+
91+
private HttpHeaders getHeaders() {
92+
HttpHeaders headers = new HttpHeaders();
93+
ResponseEntity<String> page = this.restTemplate.getForEntity("/login", String.class);
94+
assertEquals(page.getStatusCode(), HttpStatus.OK);
95+
String cookie = page
96+
.getHeaders()
97+
.getFirst("Set-Cookie");
98+
headers.set("Cookie", cookie);
99+
Pattern pattern = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*");
100+
Matcher matcher = pattern.matcher(page.getBody());
101+
assertTrue(matcher.matches());
102+
headers.set("X-CSRF-TOKEN", matcher.group(1));
103+
return headers;
104+
}
105+
106+
}

0 commit comments

Comments
 (0)