JAVA-67:renamed spring-security-mvc-boot-1 to spring-security-web-boot-1

This commit is contained in:
sampadawagde
2020-08-13 12:52:53 +05:30
parent 36a2c6edb1
commit 787bbd4f2c
87 changed files with 2 additions and 2 deletions
@@ -0,0 +1,111 @@
package com.baeldung.relationships;
import com.baeldung.relationships.repositories.TweetRepository;
import com.baeldung.relationships.repositories.UserRepository;
import com.baeldung.relationships.models.AppUser;
import com.baeldung.relationships.models.Tweet;
import com.baeldung.relationships.security.AppUserPrincipal;
import com.baeldung.relationships.util.DummyContentUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.jdbc.JdbcTestUtils;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import javax.servlet.ServletContext;
import java.util.Date;
import java.util.List;
import static org.springframework.util.Assert.isTrue;
@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration
@DirtiesContext
public class SpringDataWithSecurityIntegrationTest {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
@Autowired
private ServletContext servletContext;
private static UserRepository userRepository;
private static TweetRepository tweetRepository;
@Before
public void testInit() {
ctx.register(AppConfig.class);
ctx.setServletContext(servletContext);
ctx.refresh();
userRepository = ctx.getBean(UserRepository.class);
tweetRepository = ctx.getBean(TweetRepository.class);
List<AppUser> appUsers = (List<AppUser>) userRepository.saveAll(DummyContentUtil.generateDummyUsers());
tweetRepository.saveAll(DummyContentUtil.generateDummyTweets(appUsers));
}
/**
* This is to ensure the tables are dropped in proper order.
* After the Spring Boot 2.2.2 upgrade, DDL statements generated automatically try to drop Tweet table first.
* As a result we get org.h2.jdbc.JdbcSQLSyntaxErrorException because Tweet_Likes table depends on Tweet.
*
* @see <a href="https://stackoverflow.com/questions/59364212/integrationtest-isolation-fails-in-springboot-2-2-2-release-error-dopping-table">
* StackOverflow#59364212
* </a>
* @see <a href="https://stackoverflow.com/questions/59561551/hibernate-h2-specify-drop-table-order">
* StackOverflow#59561551
* </a>
*/
@After
public void tearDown() {
JdbcTemplate jdbcTemplate = ctx.getBean(JdbcTemplate.class);
JdbcTestUtils.dropTables(jdbcTemplate, "Tweet_Likes", "Tweet");
}
@Test
public void givenAppUser_whenLoginSuccessful_shouldUpdateLastLogin() {
AppUser appUser = userRepository.findByUsername("lionel@messi.com");
Authentication auth = new UsernamePasswordAuthenticationToken(new AppUserPrincipal(appUser), null, DummyContentUtil.getAuthorities());
SecurityContextHolder.getContext()
.setAuthentication(auth);
userRepository.updateLastLogin(new Date());
}
@Test(expected = InvalidDataAccessApiUsageException.class)
public void givenNoAppUserInSecurityContext_whenUpdateLastLoginAttempted_shouldFail() {
userRepository.updateLastLogin(new Date());
}
@Test
public void givenAppUser_whenLoginSuccessful_shouldReadMyPagedTweets() {
AppUser appUser = userRepository.findByUsername("lionel@messi.com");
Authentication auth = new UsernamePasswordAuthenticationToken(new AppUserPrincipal(appUser), null, DummyContentUtil.getAuthorities());
SecurityContextHolder.getContext()
.setAuthentication(auth);
Page<Tweet> page = null;
do {
page = tweetRepository.getMyTweetsAndTheOnesILiked(PageRequest.of(page != null ? page.getNumber() + 1 : 0, 5));
for (Tweet twt : page.getContent()) {
isTrue((twt.getOwner() == appUser.getUsername()) || (twt.getLikes()
.contains(appUser.getUsername())), "I do not have any Tweets");
}
} while (page.hasNext());
}
@Test(expected = InvalidDataAccessApiUsageException.class)
public void givenNoAppUser_whenPaginatedResultsRetrievalAttempted_shouldFail() {
Page<Tweet> page = null;
do {
page = tweetRepository.getMyTweetsAndTheOnesILiked(PageRequest.of(page != null ? page.getNumber() + 1 : 0, 5));
} while (page != null && page.hasNext());
}
}
@@ -0,0 +1,16 @@
package com.baeldung.roles;
import com.baeldung.roles.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 SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
@@ -0,0 +1,67 @@
package com.baeldung.roles.web;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.baeldung.roles.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;
// In order to execute these tests, com.baeldung.custom.Application needs to be running.
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"));
}
}
@@ -0,0 +1,89 @@
package com.baeldung.roles.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 com.baeldung.roles.custom.Application;
import com.baeldung.roles.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().isFound());
}
@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;
}
}
@@ -0,0 +1,28 @@
package com.baeldung.roles.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;
// In order to execute these tests, com.baeldung.ip.IpApplication needs to be running.
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"));
}
}