Skip to content

Commit 9dab68a

Browse files
Tian Baoqiangpivovarit
authored andcommitted
add redirection after login with Spring Security(BAEL-648) (eugenp#1214)
1 parent 9c5ecd8 commit 9dab68a

7 files changed

Lines changed: 219 additions & 1 deletion

File tree

‎spring-security-mvc-login/pom.xml‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,19 @@
152152
<scope>test</scope>
153153
</dependency>
154154

155+
<dependency>
156+
<groupId>org.springframework</groupId>
157+
<artifactId>spring-test</artifactId>
158+
<version>${org.springframework.version}</version>
159+
<scope>test</scope>
160+
</dependency>
161+
<dependency>
162+
<groupId>org.springframework.security</groupId>
163+
<artifactId>spring-security-test</artifactId>
164+
<version>${org.springframework.security.version}</version>
165+
<scope>test</scope>
166+
</dependency>
167+
155168
</dependencies>
156169

157170
<build>
@@ -222,7 +235,7 @@
222235

223236
<properties>
224237
<!-- Spring -->
225-
<org.springframework.version>4.3.5.RELEASE</org.springframework.version>
238+
<org.springframework.version>4.3.6.RELEASE</org.springframework.version>
226239
<org.springframework.security.version>4.2.1.RELEASE</org.springframework.security.version>
227240

228241
<!-- persistence -->
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package org.baeldung.controller;
2+
3+
import org.springframework.stereotype.Controller;
4+
import org.springframework.web.bind.annotation.RequestMapping;
5+
6+
import javax.servlet.http.HttpServletRequest;
7+
import javax.servlet.http.HttpServletResponse;
8+
9+
@Controller
10+
public class SecuredResourceController {
11+
12+
@RequestMapping("/secured")
13+
public void secureResource(HttpServletRequest request, HttpServletResponse response) {
14+
System.out.println("accessing secured resource");
15+
}
16+
17+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package org.baeldung.security;
2+
3+
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
4+
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
5+
6+
public class RefererAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
7+
8+
public RefererAuthenticationSuccessHandler() {
9+
super();
10+
setUseReferer(true);
11+
}
12+
13+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package org.baeldung.spring;
2+
3+
import org.springframework.context.annotation.Configuration;
4+
import org.springframework.context.annotation.Profile;
5+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
6+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
8+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
9+
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
10+
11+
@Configuration
12+
//@ImportResource({ "classpath:RedirectionWebSecurityConfig.xml" })
13+
@EnableWebSecurity
14+
@Profile("!https")
15+
public class RedirectionSecurityConfig extends WebSecurityConfigurerAdapter {
16+
17+
public RedirectionSecurityConfig() {
18+
super();
19+
}
20+
21+
@Override
22+
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
23+
auth
24+
.inMemoryAuthentication()
25+
.withUser("user1")
26+
.password("user1Pass")
27+
.roles("USER");
28+
}
29+
30+
@Override
31+
protected void configure(final HttpSecurity http) throws Exception {
32+
http
33+
.authorizeRequests()
34+
.antMatchers("/login*")
35+
.permitAll()
36+
.anyRequest()
37+
.authenticated()
38+
.and()
39+
.formLogin()
40+
.successHandler(new SavedRequestAwareAuthenticationSuccessHandler());
41+
//.successHandler(new RefererAuthenticationSuccessHandler())
42+
}
43+
44+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
3+
xsi:schemaLocation="
4+
http://www.springframework.org/schema/security
5+
http://www.springframework.org/schema/security/spring-security-4.2.xsd
6+
http://www.springframework.org/schema/beans
7+
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"
8+
>
9+
<http use-expressions="true">
10+
<intercept-url pattern="/login*" access="permitAll"/>
11+
<intercept-url pattern="/**" access="isAuthenticated()"/>
12+
13+
<form-login authentication-success-handler-ref="awareAuthenticationSuccessHandler" />
14+
</http>
15+
16+
<beans:bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler" name="awareAuthenticationSuccessHandler"/>
17+
<beans:bean class="org.baeldung.security.RefererAuthenticationSuccessHandler" name="refererHandler"/>
18+
19+
<authentication-manager>
20+
<authentication-provider>
21+
<user-service>
22+
<user name="user1" password="user1Pass" authorities="ROLE_USER"/>
23+
</user-service>
24+
</authentication-provider>
25+
</authentication-manager>
26+
27+
28+
</beans:beans>
29+
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package org.baeldung.security;
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.mock.web.MockHttpSession;
8+
import org.springframework.security.core.userdetails.UserDetails;
9+
import org.springframework.security.core.userdetails.UserDetailsService;
10+
import org.springframework.test.context.ContextConfiguration;
11+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
12+
import org.springframework.test.context.web.WebAppConfiguration;
13+
import org.springframework.test.web.servlet.MockMvc;
14+
import org.springframework.test.web.servlet.MvcResult;
15+
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
16+
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
17+
import org.springframework.web.context.WebApplicationContext;
18+
19+
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
20+
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
21+
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
22+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
23+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
24+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern;
25+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
26+
27+
@RunWith(SpringJUnit4ClassRunner.class)
28+
@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" })
29+
@WebAppConfiguration
30+
public class RedirectionSecurityIntegrationTest {
31+
32+
@Autowired private WebApplicationContext context;
33+
34+
@Autowired private UserDetailsService userDetailsService;
35+
36+
private MockMvc mvc;
37+
private UserDetails userDetails;
38+
39+
@Before
40+
public void setup() {
41+
mvc = MockMvcBuilders
42+
.webAppContextSetup(context)
43+
.apply(springSecurity())
44+
.build();
45+
userDetails = userDetailsService.loadUserByUsername("user1");
46+
}
47+
48+
@Test
49+
public void givenSecuredResource_whenAccessUnauthenticated_thenRequiresAuthentication() throws Exception {
50+
mvc
51+
.perform(get("/secured"))
52+
.andExpect(status().is3xxRedirection())
53+
.andExpect(redirectedUrlPattern("**/login"));
54+
55+
}
56+
57+
@Test
58+
public void givenCredentials_whenAccessSecuredResource_thenSuccess() throws Exception {
59+
mvc
60+
.perform(get("/secured").with(user(userDetails)))
61+
.andExpect(status().isOk());
62+
}
63+
64+
@Test
65+
public void givenAccessSecuredResource_whenAuthenticated_thenRedirectedBack() throws Exception {
66+
MockHttpServletRequestBuilder securedResourceAccess = get("/secured");
67+
MvcResult unauthenticatedResult = mvc
68+
.perform(securedResourceAccess)
69+
.andExpect(status().is3xxRedirection())
70+
.andReturn();
71+
72+
MockHttpSession session = (MockHttpSession) unauthenticatedResult
73+
.getRequest()
74+
.getSession();
75+
String loginUrl = unauthenticatedResult
76+
.getResponse()
77+
.getRedirectedUrl();
78+
mvc
79+
.perform(post(loginUrl)
80+
.param("username", userDetails.getUsername())
81+
.param("password", userDetails.getPassword())
82+
.session(session)
83+
.with(csrf()))
84+
.andExpect(status().is3xxRedirection())
85+
.andExpect(redirectedUrlPattern("**/secured"))
86+
.andReturn();
87+
88+
mvc
89+
.perform(securedResourceAccess.session(session))
90+
.andExpect(status().isOk());
91+
92+
}
93+
94+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<beans xmlns="http://www.springframework.org/schema/beans"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
4+
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
5+
6+
<context:component-scan base-package="org.baeldung.controller" />
7+
8+
</beans>

0 commit comments

Comments
 (0)