JAVA-67:renamed spring-security-mvc-boot-2 to spring-security-web-boot-2
This commit is contained in:
+108
@@ -0,0 +1,108 @@
|
||||
package com.baeldung.customlogouthandler;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.boot.web.server.LocalServerPort;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.jdbc.Sql;
|
||||
import org.springframework.test.context.jdbc.SqlGroup;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.baeldung.customlogouthandler.services.UserCache;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = { CustomLogoutApplication.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@SqlGroup({ @Sql(value = "classpath:customlogouthandler/before.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD), @Sql(value = "classpath:customlogouthandler/after.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) })
|
||||
@TestPropertySource(locations="classpath:customlogouthandler/application.properties")
|
||||
class CustomLogoutHandlerIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private TestRestTemplate restTemplate;
|
||||
|
||||
@Autowired
|
||||
private UserCache userCache;
|
||||
|
||||
@LocalServerPort
|
||||
private int port;
|
||||
|
||||
@Test
|
||||
public void whenLogin_thenUseUserCache() {
|
||||
// User cache should be empty on start
|
||||
assertThat(userCache.size()).isEqualTo(0);
|
||||
|
||||
// Request using first login
|
||||
ResponseEntity<String> response = restTemplate.withBasicAuth("user", "pass")
|
||||
.getForEntity(getLanguageUrl(), String.class);
|
||||
|
||||
assertThat(response.getBody()).contains("english");
|
||||
|
||||
// User cache must contain the user
|
||||
assertThat(userCache.size()).isEqualTo(1);
|
||||
|
||||
// Getting the session cookie
|
||||
HttpHeaders requestHeaders = new HttpHeaders();
|
||||
requestHeaders.add("Cookie", response.getHeaders()
|
||||
.getFirst(HttpHeaders.SET_COOKIE));
|
||||
|
||||
// Request with the session cookie
|
||||
response = restTemplate.exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity<String>(requestHeaders), String.class);
|
||||
assertThat(response.getBody()).contains("english");
|
||||
|
||||
// Logging out using the session cookies
|
||||
response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity<String>(requestHeaders), String.class);
|
||||
assertThat(response.getStatusCode()
|
||||
.value()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLogout_thenCacheIsEmpty() {
|
||||
// User cache should be empty on start
|
||||
assertThat(userCache.size()).isEqualTo(0);
|
||||
|
||||
// Request using first login
|
||||
ResponseEntity<String> response = restTemplate.withBasicAuth("user", "pass")
|
||||
.getForEntity(getLanguageUrl(), String.class);
|
||||
|
||||
assertThat(response.getBody()).contains("english");
|
||||
|
||||
// User cache must contain the user
|
||||
assertThat(userCache.size()).isEqualTo(1);
|
||||
|
||||
// Getting the session cookie
|
||||
HttpHeaders requestHeaders = new HttpHeaders();
|
||||
requestHeaders.add("Cookie", response.getHeaders()
|
||||
.getFirst(HttpHeaders.SET_COOKIE));
|
||||
|
||||
// Logging out using the session cookies
|
||||
response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity<String>(requestHeaders), String.class);
|
||||
assertThat(response.getStatusCode()
|
||||
.value()).isEqualTo(200);
|
||||
|
||||
// User cache must be empty now
|
||||
// this is the reaction on custom logout filter execution
|
||||
assertThat(userCache.size()).isEqualTo(0);
|
||||
|
||||
// Assert unauthorized request
|
||||
response = restTemplate.exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity<String>(requestHeaders), String.class);
|
||||
assertThat(response.getStatusCode()
|
||||
.value()).isEqualTo(401);
|
||||
}
|
||||
|
||||
private String getLanguageUrl() {
|
||||
return "http://localhost:" + port + "/user/language";
|
||||
}
|
||||
|
||||
private String getLogoutUrl() {
|
||||
return "http://localhost:" + port + "/user/logout";
|
||||
}
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.jdbcauthentication.h2;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = H2JdbcAuthenticationApplication.class)
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.jdbcauthentication.h2.web;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import io.restassured.authentication.FormAuthConfig;
|
||||
import io.restassured.filter.session.SessionFilter;
|
||||
|
||||
/**
|
||||
* This Live Test requires the H2JdbcAuthenticationApplication application to be up and running
|
||||
*/
|
||||
public class UserControllerLiveTest {
|
||||
|
||||
private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal";
|
||||
|
||||
@Test
|
||||
public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception {
|
||||
SessionFilter filter = new SessionFilter();
|
||||
given().auth()
|
||||
.form("user", "pass", new FormAuthConfig("/login", "username", "password").withCsrfFieldName("_csrf"))
|
||||
.and()
|
||||
.filter(filter)
|
||||
.when()
|
||||
.get(PRINCIPAL_SVC_URL)
|
||||
.then()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.and()
|
||||
.body("authorities[0].authority", is("ROLE_USER"))
|
||||
.body("principal.username", is("user"))
|
||||
.body("name", is("user"));
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.jdbcauthentication.mysql.web;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
/**
|
||||
* This Live Test requires:
|
||||
* * a MySql instance running, that allows a 'root' user with password 'pass', and with a database named jdbc_authentication
|
||||
* (e.g. with the following command `docker run -p 3306:3306 --name bael-mysql -e MYSQL_ROOT_PASSWORD=pass -e MYSQL_DATABASE=jdbc_authentication mysql:latest`)
|
||||
* * the service up and running
|
||||
*
|
||||
*/
|
||||
public class UserControllerLiveTest {
|
||||
|
||||
private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal";
|
||||
|
||||
@Test
|
||||
public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception {
|
||||
given().auth()
|
||||
.preemptive()
|
||||
.basic("user@email.com", "pass")
|
||||
.when()
|
||||
.get(PRINCIPAL_SVC_URL)
|
||||
.then()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.and()
|
||||
.body("authorities[0].authority", is("ROLE_USER"))
|
||||
.body("principal.username", is("user@email.com"))
|
||||
.body("name", is("user@email.com"));
|
||||
}
|
||||
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.jdbcauthentication.postgre.web;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
/**
|
||||
* This Live Test requires:
|
||||
* * a PostgreSQL instance running, that allows a 'root' user with password 'pass', and with a database named jdbc_authentication
|
||||
* (e.g. with the following command `docker run -p 5432:5432 --name bael-postgre -e POSTGRES_PASSWORD=pass -e POSTGRES_DB=jdbc_authentication postgres:latest`)
|
||||
* * the service up and running
|
||||
*
|
||||
*/
|
||||
public class UserControllerLiveTest {
|
||||
|
||||
private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal";
|
||||
|
||||
@Test
|
||||
public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception {
|
||||
given().auth()
|
||||
.preemptive()
|
||||
.basic("user", "pass")
|
||||
.when()
|
||||
.get(PRINCIPAL_SVC_URL)
|
||||
.then()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.and()
|
||||
.body("authorities[0].authority", is("ROLE_USER"))
|
||||
.body("principal.username", is("user"))
|
||||
.body("name", is("user"));
|
||||
}
|
||||
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.web;
|
||||
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.ssl.SSLContextBuilder;
|
||||
import com.baeldung.ssl.HttpsEnabledApplication;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import java.util.Collections;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = HttpsEnabledApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
|
||||
@ActiveProfiles("ssl")
|
||||
public class HttpsApplicationIntegrationTest {
|
||||
|
||||
private static final String WELCOME_URL = "https://localhost:8443/welcome";
|
||||
|
||||
@Value("${trust.store}")
|
||||
private Resource trustStore;
|
||||
|
||||
@Value("${trust.store.password}")
|
||||
private String trustStorePassword;
|
||||
|
||||
@Test
|
||||
public void whenGETanHTTPSResource_thenCorrectResponse() throws Exception {
|
||||
ResponseEntity<String> response = restTemplate().getForEntity(WELCOME_URL, String.class, Collections.emptyMap());
|
||||
|
||||
assertEquals("<h1>Welcome to Secured Site</h1>", response.getBody());
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
}
|
||||
|
||||
RestTemplate restTemplate() throws Exception {
|
||||
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray())
|
||||
.build();
|
||||
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
|
||||
HttpClient httpClient = HttpClients.custom()
|
||||
.setSSLSocketFactory(socketFactory)
|
||||
.build();
|
||||
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
|
||||
return new RestTemplate(factory);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.web;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import com.baeldung.multipleauthproviders.MultipleAuthProvidersApplication;
|
||||
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.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = MultipleAuthProvidersApplication.class)
|
||||
public class MultipleAuthProvidersApplicationIntegrationTest {
|
||||
@Autowired
|
||||
private TestRestTemplate restTemplate;
|
||||
|
||||
@Test
|
||||
public void givenMemUsers_whenGetPingWithValidUser_thenOk() {
|
||||
ResponseEntity<String> result = makeRestCallToGetPing("memuser", "pass");
|
||||
|
||||
assertThat(result.getStatusCodeValue()).isEqualTo(200);
|
||||
assertThat(result.getBody()).isEqualTo("OK");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExternalUsers_whenGetPingWithValidUser_thenOK() {
|
||||
ResponseEntity<String> result = makeRestCallToGetPing("externaluser", "pass");
|
||||
|
||||
assertThat(result.getStatusCodeValue()).isEqualTo(200);
|
||||
assertThat(result.getBody()).isEqualTo("OK");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthProviders_whenGetPingWithNoCred_then401() {
|
||||
ResponseEntity<String> result = makeRestCallToGetPing();
|
||||
|
||||
assertThat(result.getStatusCodeValue()).isEqualTo(401);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthProviders_whenGetPingWithBadCred_then401() {
|
||||
ResponseEntity<String> result = makeRestCallToGetPing("user", "bad_password");
|
||||
|
||||
assertThat(result.getStatusCodeValue()).isEqualTo(401);
|
||||
}
|
||||
|
||||
private ResponseEntity<String> makeRestCallToGetPing(String username, String password) {
|
||||
return restTemplate.withBasicAuth(username, password)
|
||||
.getForEntity("/api/ping", String.class, Collections.emptyMap());
|
||||
}
|
||||
|
||||
private ResponseEntity<String> makeRestCallToGetPing() {
|
||||
return restTemplate.getForEntity("/api/ping", String.class, Collections.emptyMap());
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.web;
|
||||
|
||||
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.security.web.FilterChainProxy;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
import com.baeldung.multipleentrypoints.MultipleEntryPointsApplication;
|
||||
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@WebAppConfiguration
|
||||
@SpringBootTest(classes = MultipleEntryPointsApplication.class)
|
||||
public class MultipleEntryPointsIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
|
||||
@Autowired
|
||||
private FilterChainProxy springSecurityFilterChain;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilter(springSecurityFilterChain).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTestAdminCredentials_thenOk() throws Exception {
|
||||
mockMvc.perform(get("/admin/myAdminPage")).andExpect(status().isUnauthorized());
|
||||
|
||||
mockMvc.perform(get("/admin/myAdminPage").with(httpBasic("admin", "adminPass"))).andExpect(status().isOk());
|
||||
|
||||
mockMvc.perform(get("/user/myUserPage").with(user("admin").password("adminPass").roles("ADMIN"))).andExpect(status().isForbidden());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTestUserCredentials_thenOk() throws Exception {
|
||||
mockMvc.perform(get("/user/general/myUserPage")).andExpect(status().isFound());
|
||||
|
||||
mockMvc.perform(get("/user/general/myUserPage").with(user("user").password("userPass").roles("USER"))).andExpect(status().isOk());
|
||||
|
||||
mockMvc.perform(get("/admin/myAdminPage").with(user("user").password("userPass").roles("USER"))).andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnyUser_whenGetGuestPage_thenOk() throws Exception {
|
||||
mockMvc.perform(get("/guest/myGuestPage")).andExpect(status().isOk());
|
||||
|
||||
mockMvc.perform(get("/guest/myGuestPage").with(user("user").password("userPass").roles("USER"))).andExpect(status().isOk());
|
||||
|
||||
mockMvc.perform(get("/guest/myGuestPage").with(httpBasic("admin", "adminPass"))).andExpect(status().isOk());
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
delete from users;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
spring.datasource.driver-class-name=org.h2.Driver
|
||||
spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
|
||||
spring.datasource.username=test
|
||||
spring.datasource.password=test
|
||||
+1
@@ -0,0 +1 @@
|
||||
insert into users (login, password, role, language) values ('user', '{noop}pass', 'ROLE_USER', 'english');
|
||||
Reference in New Issue
Block a user