[BAEL-3066] Spring Security: Exploring JDBC Authentication (#7441)
* created multi-module project from spring-security-mvc-boot * Added JDBC Authentication application to spring-security-mvc-boot-default * Added JDBC Authentication application to spring-security-mvc-boot-mysql * Added JDBC Authentication application to spring-security-mvc-boot-postgre * adding new modules to parent spring-security-mvc-boot module, reformatting sql scripts, and added form fields to H2 LiveTest
This commit is contained in:
@@ -1,16 +0,0 @@
|
||||
package org.baeldung;
|
||||
|
||||
import org.baeldung.custom.Application;
|
||||
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 = Application.class)
|
||||
public class SpringContextIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package org.baeldung.web;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.baeldung.custom.persistence.model.Foo;
|
||||
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.authentication.FormAuthConfig;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
|
||||
public class ApplicationLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenUserWithReadPrivilegeAndHasPermission_whenGetFooById_thenOK() {
|
||||
final Response response = givenAuth("john", "123").get("http://localhost:8082/foos/1");
|
||||
assertEquals(200, response.getStatusCode());
|
||||
assertTrue(response.asString().contains("id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserWithNoWritePrivilegeAndHasPermission_whenPostFoo_thenForbidden() {
|
||||
final Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8082/foos");
|
||||
assertEquals(403, response.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserWithWritePrivilegeAndHasPermission_whenPostFoo_thenOk() {
|
||||
final Response response = givenAuth("tom", "111").and().body(new Foo("sample")).and().contentType(MediaType.APPLICATION_JSON_VALUE).post("http://localhost:8082/foos");
|
||||
assertEquals(201, response.getStatusCode());
|
||||
assertTrue(response.asString().contains("id"));
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void givenUserMemberInOrganization_whenGetOrganization_thenOK() {
|
||||
final Response response = givenAuth("john", "123").get("http://localhost:8082/organizations/1");
|
||||
assertEquals(200, response.getStatusCode());
|
||||
assertTrue(response.asString().contains("id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserMemberNotInOrganization_whenGetOrganization_thenForbidden() {
|
||||
final Response response = givenAuth("john", "123").get("http://localhost:8082/organizations/2");
|
||||
assertEquals(403, response.getStatusCode());
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void givenDisabledSecurityExpression_whenGetFooByName_thenError() {
|
||||
final Response response = givenAuth("john", "123").get("http://localhost:8082/foos?name=sample");
|
||||
assertEquals(500, response.getStatusCode());
|
||||
assertTrue(response.asString().contains("method hasAuthority() not allowed"));
|
||||
}
|
||||
|
||||
//
|
||||
private RequestSpecification givenAuth(String username, String password) {
|
||||
return RestAssured.given().log().uri().auth().form(username, password, new FormAuthConfig("/login","username","password"));
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
package org.baeldung.web;
|
||||
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.baeldung.custom.Application;
|
||||
import org.baeldung.custom.persistence.model.Foo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.test.context.support.WithAnonymousUser;
|
||||
import org.springframework.security.test.context.support.WithUserDetails;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@SpringBootTest(classes = { Application.class })
|
||||
@AutoConfigureMockMvc
|
||||
public class CustomUserDetailsServiceIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mvc;
|
||||
|
||||
@Test
|
||||
@WithUserDetails("john")
|
||||
public void givenUserWithReadPermissions_whenRequestUserInfo_thenRetrieveUserData() throws Exception {
|
||||
this.mvc.perform(get("/user").with(csrf()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.user.privileges[0].name").value("FOO_READ_PRIVILEGE"))
|
||||
.andExpect(jsonPath("$.user.organization.name").value("FirstOrg"))
|
||||
.andExpect(jsonPath("$.user.username").value("john"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUserDetails("tom")
|
||||
public void givenUserWithWritePermissions_whenRequestUserInfo_thenRetrieveUserData() throws Exception {
|
||||
this.mvc.perform(get("/user").with(csrf()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.user.privileges").isArray())
|
||||
.andExpect(jsonPath("$.user.organization.name").value("SecondOrg"))
|
||||
.andExpect(jsonPath("$.user.username").value("tom"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUserDetails("john")
|
||||
public void givenUserWithReadPermissions_whenRequestFoo_thenRetrieveSampleFoo() throws Exception {
|
||||
this.mvc.perform(get("/foos/1").with(csrf()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Sample"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithAnonymousUser
|
||||
public void givenAnonymous_whenRequestFoo_thenRetrieveUnauthorized() throws Exception {
|
||||
this.mvc.perform(get("/foos/1").with(csrf()))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUserDetails("john")
|
||||
public void givenUserWithReadPermissions_whenCreateNewFoo_thenForbiddenStatusRetrieved() throws Exception {
|
||||
this.mvc.perform(post("/foos").with(csrf())
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
|
||||
.content(asJsonString(new Foo())))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUserDetails("tom")
|
||||
public void givenUserWithWritePermissions_whenCreateNewFoo_thenOkStatusRetrieved() throws Exception {
|
||||
this.mvc.perform(post("/foos").with(csrf())
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
|
||||
.content(asJsonString(new Foo())))
|
||||
.andExpect(status().isCreated());
|
||||
}
|
||||
|
||||
private static String asJsonString(final Object obj) throws Exception {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String jsonContent = mapper.writeValueAsString(obj);
|
||||
return jsonContent;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package org.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 org.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);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package org.baeldung.web;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.response.Response;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
|
||||
public class IpLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenUser_whenGetHomePage_thenOK() {
|
||||
final Response response = RestAssured.given().auth().form("john", "123").get("http://localhost:8082/");
|
||||
assertEquals(200, response.getStatusCode());
|
||||
assertTrue(response.asString().contains("Welcome"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserWithWrongIP_whenGetFooById_thenForbidden() {
|
||||
final Response response = RestAssured.given().auth().form("john", "123").get("http://localhost:8082/foos/1");
|
||||
assertEquals(403, response.getStatusCode());
|
||||
assertTrue(response.asString().contains("Forbidden"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package org.baeldung.web;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import org.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());
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package org.baeldung.web;
|
||||
|
||||
import org.baeldung.multipleentrypoints.MultipleEntryPointsApplication;
|
||||
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 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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user