BAEL-20886: Move spring-boot-security into spring-boot-modules
This commit is contained in:
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.integrationtesting;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
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.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
public class SecuredControllerRestTemplateIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private TestRestTemplate template;
|
||||
|
||||
@Test
|
||||
public void givenRequestOnPrivateService_shouldFailWith401() throws Exception {
|
||||
ResponseEntity<String> result = template.getForEntity("/private/hello", String.class);
|
||||
assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception {
|
||||
ResponseEntity<String> result = template.withBasicAuth("spring", "secret")
|
||||
.getForEntity("/private/hello", String.class);
|
||||
assertEquals(HttpStatus.OK, result.getStatusCode());
|
||||
}
|
||||
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.integrationtesting;
|
||||
|
||||
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
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.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
public class SecuredControllerSpringBootIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext context;
|
||||
|
||||
private MockMvc mvc;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mvc = MockMvcBuilders
|
||||
.webAppContextSetup(context)
|
||||
.apply(springSecurity())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestOnPrivateService_shouldFailWith401() throws Exception {
|
||||
mvc.perform(get("/private/hello")
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@WithMockUser("spring")
|
||||
@Test
|
||||
public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception {
|
||||
mvc.perform(get("/private/hello")
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.integrationtesting;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import com.baeldung.integrationtesting.SecuredController;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@WebMvcTest(SecuredController.class)
|
||||
public class SecuredControllerWebMvcIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mvc;
|
||||
|
||||
@Test
|
||||
public void givenRequestOnPrivateService_shouldFailWith401() throws Exception {
|
||||
mvc.perform(get("/private/hello")
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@WithMockUser(value = "spring")
|
||||
@Test
|
||||
public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception {
|
||||
mvc.perform(get("/private/hello")
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.integrationtesting;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
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.authentication.AuthenticationCredentialsNotFoundException;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.integrationtesting.SecuredService;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class SecuredMethodSpringBootIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private SecuredService service;
|
||||
|
||||
@Test(expected = AuthenticationCredentialsNotFoundException.class)
|
||||
public void givenUnauthenticated_whenCallService_thenThrowsException() {
|
||||
service.sayHelloSecured();
|
||||
}
|
||||
|
||||
@WithMockUser(username="spring")
|
||||
@Test
|
||||
public void givenAuthenticated_whenCallServiceWithSecured_thenOk() {
|
||||
assertThat(service.sayHelloSecured()).isNotBlank();
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.springbootsecurity.autoconfig.config;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
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.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.springbootsecurity.autoconfig.SpringBootSecurityApplication;
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootSecurityApplication.class)
|
||||
public class BasicConfigurationIntegrationTest {
|
||||
|
||||
TestRestTemplate restTemplate;
|
||||
URL base;
|
||||
|
||||
@LocalServerPort int port;
|
||||
|
||||
@Before
|
||||
public void setUp() throws MalformedURLException {
|
||||
restTemplate = new TestRestTemplate("user", "password");
|
||||
base = new URL("http://localhost:" + port);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoggedUserRequestsHomePage_ThenSuccess() throws IllegalStateException, IOException {
|
||||
ResponseEntity<String> response = restTemplate.getForEntity(base.toString(), String.class);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
assertTrue(response
|
||||
.getBody()
|
||||
.contains("Baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUserWithWrongCredentials_thenUnauthorizedPage() throws IllegalStateException, IOException {
|
||||
restTemplate = new TestRestTemplate("user", "wrongpassword");
|
||||
ResponseEntity<String> response = restTemplate.getForEntity(base.toString(), String.class);
|
||||
|
||||
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
|
||||
assertNull(response.getBody());
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package com.baeldung.springbootsecurity.oauth2server;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.web.server.LocalServerPort;
|
||||
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
|
||||
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
|
||||
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static java.util.Collections.singletonList;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootAuthorizationServerApplication.class)
|
||||
@ActiveProfiles("authz")
|
||||
public class CustomConfigAuthorizationServerIntegrationTest extends OAuth2IntegrationTestSupport {
|
||||
|
||||
@LocalServerPort
|
||||
private int port;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
base = new URL("http://localhost:" + port);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() {
|
||||
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read"));
|
||||
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
|
||||
|
||||
OAuth2AccessToken accessToken = restTemplate.getAccessToken();
|
||||
|
||||
assertNotNull(accessToken);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOAuth2Context_whenAccessingAuthentication_ThenRespondTokenDetails() {
|
||||
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read"));
|
||||
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
|
||||
|
||||
String authentication = executeGetRequest(restTemplate, "/authentication");
|
||||
|
||||
Pattern pattern = Pattern.compile("\\{\"remoteAddress\":\".*" +
|
||||
"\",\"sessionId\":null,\"tokenValue\":\".*" +
|
||||
"\",\"tokenType\":\"Bearer\",\"decodedDetails\":null}");
|
||||
assertTrue("authentication", pattern.matcher(authentication).matches());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOAuth2Context_whenAccessingPrincipal_ThenRespondBaeldung() {
|
||||
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read"));
|
||||
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
|
||||
|
||||
String principal = executeGetRequest(restTemplate, "/principal");
|
||||
|
||||
assertEquals("baeldung", principal);
|
||||
}
|
||||
|
||||
@Test(expected = OAuth2AccessDeniedException.class)
|
||||
public void givenOAuth2Context_whenAccessTokenIsRequestedWithInvalidException_ThenExceptionIsThrown() {
|
||||
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("write"));
|
||||
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
|
||||
|
||||
restTemplate.getAccessToken();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOAuth2Context_whenAccessTokenIsRequestedByClientWithWriteScope_ThenAccessTokenIsNotNull() {
|
||||
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung-admin", singletonList("write"));
|
||||
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
|
||||
|
||||
OAuth2AccessToken accessToken = restTemplate.getAccessToken();
|
||||
|
||||
assertNotNull(accessToken);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.springbootsecurity.oauth2server;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
|
||||
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootAuthorizationServerApplication.class,
|
||||
properties = { "security.oauth2.client.client-id=client", "security.oauth2.client.client-secret=baeldung" })
|
||||
public class DefaultConfigAuthorizationServerIntegrationTest extends OAuth2IntegrationTestSupport {
|
||||
|
||||
@Test
|
||||
public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() {
|
||||
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("client", asList("read", "write"));
|
||||
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
|
||||
|
||||
OAuth2AccessToken accessToken = restTemplate.getAccessToken();
|
||||
|
||||
assertNotNull(accessToken);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.springbootsecurity.oauth2server;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
|
||||
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
|
||||
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
|
||||
import org.springframework.web.client.RequestCallback;
|
||||
import org.springframework.web.client.ResponseExtractor;
|
||||
|
||||
import java.net.URL;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.List;
|
||||
|
||||
import static java.lang.String.format;
|
||||
import static java.util.Collections.singletonList;
|
||||
import static org.springframework.http.HttpMethod.GET;
|
||||
|
||||
public class OAuth2IntegrationTestSupport {
|
||||
|
||||
public static final ResponseExtractor<String> EXTRACT_BODY_AS_STRING = clientHttpResponse ->
|
||||
IOUtils.toString(clientHttpResponse.getBody(), Charset.defaultCharset());
|
||||
private static final RequestCallback DO_NOTHING_CALLBACK = request -> {
|
||||
};
|
||||
|
||||
@Value("${local.server.port}")
|
||||
protected int port;
|
||||
|
||||
protected URL base;
|
||||
|
||||
protected ClientCredentialsResourceDetails getClientCredentialsResourceDetails(final String clientId, final List<String> scopes) {
|
||||
ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
|
||||
resourceDetails.setAccessTokenUri(format("http://localhost:%d/oauth/token", port));
|
||||
resourceDetails.setClientId(clientId);
|
||||
resourceDetails.setClientSecret("baeldung");
|
||||
resourceDetails.setScope(scopes);
|
||||
resourceDetails.setGrantType("client_credentials");
|
||||
return resourceDetails;
|
||||
}
|
||||
|
||||
protected OAuth2RestTemplate getOAuth2RestTemplate(final ClientCredentialsResourceDetails resourceDetails) {
|
||||
DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();
|
||||
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails, clientContext);
|
||||
restTemplate.setMessageConverters(singletonList(new MappingJackson2HttpMessageConverter()));
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
protected String executeGetRequest(OAuth2RestTemplate restTemplate, String path) {
|
||||
return restTemplate.execute(base.toString() + path, GET, DO_NOTHING_CALLBACK, EXTRACT_BODY_AS_STRING);
|
||||
}
|
||||
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.springsecuritytaglibs;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
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.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SpringBootSecurityTagLibsApplication.class)
|
||||
public class HomeControllerUnitTest {
|
||||
|
||||
@Autowired
|
||||
private TestRestTemplate restTemplate;
|
||||
|
||||
@Test
|
||||
public void whenUserIsAuthenticatedThenAuthenticatedSectionsShowOnSite() throws Exception {
|
||||
String body = this.restTemplate.withBasicAuth("testUser", "password")
|
||||
.getForEntity("/", String.class)
|
||||
.getBody();
|
||||
|
||||
// test <sec:authorize access="!isAuthenticated()">
|
||||
assertFalse(body.contains("Login"));
|
||||
|
||||
// test <sec:authorize access="isAuthenticated()">
|
||||
assertTrue(body.contains("Logout"));
|
||||
|
||||
// test <sec:authorize access="hasRole('ADMIN')">
|
||||
assertTrue(body.contains("Manage Users"));
|
||||
|
||||
// test <sec:authentication property="principal.username" />
|
||||
assertTrue(body.contains("testUser"));
|
||||
|
||||
// test <sec:authorize url="/adminOnlyURL">
|
||||
assertTrue(body.contains("<a href=\"/userManagement\">"));
|
||||
|
||||
// test <sec:csrfInput />
|
||||
assertTrue(body.contains("<input type=\"hidden\" name=\"_csrf\" value=\""));
|
||||
|
||||
// test <sec:csrfMetaTags />
|
||||
assertTrue(body.contains("<meta name=\"_csrf_parameter\" content=\"_csrf\" />"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUserIsNotAuthenticatedThenOnlyAnonymousSectionsShowOnSite() throws Exception {
|
||||
String body = this.restTemplate.getForEntity("/", String.class)
|
||||
.getBody();
|
||||
|
||||
// test <sec:authorize access="!isAuthenticated()">
|
||||
assertTrue(body.contains("Login"));
|
||||
|
||||
// test <sec:authorize access="isAuthenticated()">
|
||||
assertFalse(body.contains("Logout"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user