Skip to content

Commit

Permalink
BAEL-1969 spring security for spring boot integration tests (eugenp#5074
Browse files Browse the repository at this point in the history
)

* BAEL-1969 spring security for spring boot integration tests

* BAEL-1969 spring security for spring boot integration tests
  • Loading branch information
chrisoberle authored and pivovarit committed Sep 2, 2018
1 parent b7aa6a2 commit 212e6fe
Show file tree
Hide file tree
Showing 9 changed files with 248 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.baeldung.integrationtesting;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;

@Configuration
@EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true)
public class MethodSecurityConfigurer extends GlobalMethodSecurityConfiguration {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.baeldung.integrationtesting;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SecuredApplication {

public static void main(String[] args) {
SpringApplication.run(SecuredApplication.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.baeldung.integrationtesting;

import java.util.Arrays;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SecuredController {

@GetMapping("/public/hello")
public List<String> publicHello() {
return Arrays.asList("Hello", "World", "from", "Public");
}

@GetMapping("/private/hello")
public List<String> privateHello() {
return Arrays.asList("Hello", "World", "from", "Private");
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.baeldung.integrationtesting;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

@Service
public class SecuredService {

@PreAuthorize("authenticated")
public String sayHelloSecured() {
return "Hello user.";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.baeldung.integrationtesting;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("spring")
.password("secret")
.roles("USER");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/private/**")
.hasRole("USER")
.antMatchers("/public/**")
.permitAll()
.and()
.httpBasic();
}


}
Original file line number Diff line number Diff line change
@@ -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());
}

}
Original file line number Diff line number Diff line change
@@ -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());
}

}
Original file line number Diff line number Diff line change
@@ -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());
}

}
Original file line number Diff line number Diff line change
@@ -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();
}
}

0 comments on commit 212e6fe

Please sign in to comment.