Skip to content

Commit 44b61ab

Browse files
danielguedesbmaibin
authored andcommitted
BAEL-1914 (eugenp#4713)
* Server Sent Events example using Spring Webflux and React * spring security custom AuthenticationFailureHandler * refactor * moved SSE to branch * BAEL-1914 * remove pom properties
1 parent c5c23ae commit 44b61ab

4 files changed

Lines changed: 171 additions & 0 deletions

File tree

‎spring-boot-security/pom.xml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,11 @@
5555
<artifactId>spring-security-test</artifactId>
5656
<scope>test</scope>
5757
</dependency>
58+
<dependency>
59+
<groupId>org.springframework.security</groupId>
60+
<artifactId>spring-security-test</artifactId>
61+
<scope>test</scope>
62+
</dependency>
5863
</dependencies>
5964

6065
<build>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.baeldung.springbootsecurity.form_login;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecurity.form_login")
7+
public class SpringBootSecurityApplication {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run(SpringBootSecurityApplication.class, args);
11+
}
12+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.baeldung.springbootsecurity.form_login.configuration;
2+
3+
import com.fasterxml.jackson.databind.ObjectMapper;
4+
import org.springframework.context.annotation.Bean;
5+
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.http.HttpStatus;
7+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
8+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
9+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
10+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
11+
import org.springframework.security.core.AuthenticationException;
12+
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
13+
14+
import javax.servlet.ServletException;
15+
import javax.servlet.http.HttpServletRequest;
16+
import javax.servlet.http.HttpServletResponse;
17+
import java.io.IOException;
18+
import java.util.Calendar;
19+
import java.util.HashMap;
20+
import java.util.Map;
21+
22+
@Configuration
23+
@EnableWebSecurity
24+
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
25+
26+
@Override
27+
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
28+
auth
29+
.inMemoryAuthentication()
30+
.withUser("baeldung")
31+
.password("baeldung")
32+
.roles("USER");
33+
}
34+
35+
@Override
36+
protected void configure(HttpSecurity http) throws Exception {
37+
http
38+
.authorizeRequests()
39+
.anyRequest()
40+
.authenticated()
41+
.and()
42+
.formLogin()
43+
.failureHandler(customAuthenticationFailureHandler());
44+
}
45+
46+
@Bean
47+
public AuthenticationFailureHandler customAuthenticationFailureHandler() {
48+
return new CustomAuthenticationFailureHandler();
49+
}
50+
51+
/**
52+
* Custom AuthenticationFailureHandler
53+
*/
54+
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
55+
private final ObjectMapper objectMapper = new ObjectMapper();
56+
57+
@Override
58+
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
59+
response.setStatus(HttpStatus.UNAUTHORIZED.value());
60+
Map<String, Object> data = new HashMap<>();
61+
data.put("timestamp", Calendar.getInstance().getTime());
62+
data.put("exception", exception.getMessage());
63+
64+
response.getOutputStream().println(objectMapper.writeValueAsString(data));
65+
}
66+
}
67+
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package com.baeldung.springbootsecurity.form_login;
2+
3+
import org.junit.Before;
4+
import org.junit.Test;
5+
import org.junit.runner.RunWith;
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
import org.springframework.boot.test.context.SpringBootTest;
8+
import org.springframework.test.context.junit4.SpringRunner;
9+
import org.springframework.test.web.servlet.MockMvc;
10+
import org.springframework.test.web.servlet.MvcResult;
11+
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
12+
import org.springframework.web.context.WebApplicationContext;
13+
14+
import javax.servlet.Filter;
15+
16+
import static org.junit.Assert.assertTrue;
17+
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
18+
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
19+
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
20+
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
21+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
22+
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
23+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
24+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
25+
26+
@RunWith(SpringRunner.class)
27+
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = com.baeldung.springbootsecurity.form_login.SpringBootSecurityApplication.class)
28+
public class FormLoginIntegrationTest {
29+
30+
@Autowired
31+
private WebApplicationContext context;
32+
33+
@Autowired
34+
private Filter springSecurityFilterChain;
35+
36+
private MockMvc mvc;
37+
38+
@Before
39+
public void setup() {
40+
mvc = MockMvcBuilders
41+
.webAppContextSetup(context)
42+
.addFilters(springSecurityFilterChain)
43+
.build();
44+
}
45+
46+
@Test
47+
public void givenRequestWithoutSessionOrCsrfToken_shouldFailWith403() throws Exception {
48+
mvc
49+
.perform(post("/"))
50+
.andExpect(status().isForbidden());
51+
}
52+
53+
@Test
54+
public void givenRequestWithInvalidCsrfToken_shouldFailWith403() throws Exception {
55+
mvc
56+
.perform(post("/").with(csrf().useInvalidToken()))
57+
.andExpect(status().isForbidden());
58+
}
59+
60+
@Test
61+
public void givenRequestWithValidCsrfTokenAndWithoutSessionToken_shouldReceive302WithLocationHeaderToLoginPage() throws Exception {
62+
MvcResult mvcResult = mvc.perform(post("/").with(csrf())).andReturn();
63+
assertTrue(mvcResult.getResponse().getStatus() == 302);
64+
assertTrue(mvcResult.getResponse().getHeader("Location").contains("login"));
65+
}
66+
67+
@Test
68+
public void givenValidRequestWithValidCredentials_shouldLoginSuccessfully() throws Exception {
69+
mvc
70+
.perform(formLogin().user("baeldung").password("baeldung"))
71+
.andExpect(status().isFound())
72+
.andExpect(redirectedUrl("/"))
73+
.andExpect(authenticated().withUsername("baeldung"));
74+
}
75+
76+
@Test
77+
public void givenValidRequestWithInvalidCredentials_shouldFailWith401() throws Exception {
78+
MvcResult result = mvc
79+
.perform(formLogin().user("random").password("random"))
80+
.andExpect(status().isUnauthorized())
81+
.andDo(print())
82+
.andExpect(unauthenticated())
83+
.andReturn();
84+
85+
assertTrue(result.getResponse().getContentAsString().contains("Bad credentials"));
86+
}
87+
}

0 commit comments

Comments
 (0)