From 84d820a594f0f8cbee34f4f72096770bf30ac62b Mon Sep 17 00:00:00 2001 From: Cicio Flaviu Date: Wed, 10 Jun 2020 21:39:36 +0300 Subject: [PATCH 1/2] BAEL-4018 Spring Security - Already logged in user redirect from the login page --- .../loginredirect/LoginPageFilter.java | 39 ++++++++++++++++ .../loginredirect/LoginPageInterceptor.java | 39 ++++++++++++++++ .../LoginRedirectApplication.java | 12 +++++ .../loginredirect/LoginRedirectMvcConfig.java | 14 ++++++ .../LoginRedirectSecurityConfig.java | 43 +++++++++++++++++ .../loginredirect/UsersController.java | 32 +++++++++++++ .../spring-security-login-redirect.xml | 46 +++++++++++++++++++ .../resources/templates/userMainPage.html | 10 ++++ 8 files changed, 235 insertions(+) create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageFilter.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageInterceptor.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectApplication.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectMvcConfig.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectSecurityConfig.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/UsersController.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/resources/spring-security-login-redirect.xml create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/userMainPage.html diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageFilter.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageFilter.java new file mode 100644 index 0000000000..635f811e7a --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageFilter.java @@ -0,0 +1,39 @@ +package com.baeldung.loginredirect; + +import org.apache.http.HttpStatus; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.GenericFilterBean; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +class LoginPageFilter extends GenericFilterBean { + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + if (isAuthenticated() && ((HttpServletRequest) request).getRequestURI().equals("/loginUser")) { + + String encodedRedirectURL = ((HttpServletResponse) response).encodeRedirectURL( + ((HttpServletRequest) request).getContextPath() + "/userMainPage"); + + ((HttpServletResponse) response).setStatus(HttpStatus.SC_TEMPORARY_REDIRECT); + ((HttpServletResponse) response).setHeader("Location", encodedRedirectURL); + } + chain.doFilter(request, response); + } + + private boolean isAuthenticated() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null || authentication instanceof AnonymousAuthenticationToken) { + return false; + } + return authentication.isAuthenticated(); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageInterceptor.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageInterceptor.java new file mode 100644 index 0000000000..f8fbe76b61 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageInterceptor.java @@ -0,0 +1,39 @@ +package com.baeldung.loginredirect; + +import org.apache.http.HttpStatus; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; +import org.springframework.web.util.UrlPathHelper; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +class LoginPageInterceptor extends HandlerInterceptorAdapter { + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + + UrlPathHelper urlPathHelper = new UrlPathHelper(); + if (urlPathHelper.getLookupPathForRequest(request).equals("/loginUser") && isAuthenticated()) { + + String encodedRedirectURL = response.encodeRedirectURL( + request.getContextPath() + "/userMainPage"); + response.setStatus(HttpStatus.SC_TEMPORARY_REDIRECT); + response.setHeader("Location", encodedRedirectURL); + + return false; + } else { + return true; + } + } + + private boolean isAuthenticated() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null || authentication instanceof AnonymousAuthenticationToken) { + return false; + } + return authentication.isAuthenticated(); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectApplication.java new file mode 100644 index 0000000000..b7f9863775 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.loginredirect; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +//@ImportResource({"classpath*:spring-security-login-redirect.xml"}) +class LoginRedirectApplication { + public static void main(String[] args) { + SpringApplication.run(LoginRedirectApplication.class, args); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectMvcConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectMvcConfig.java new file mode 100644 index 0000000000..ca2ddcb020 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectMvcConfig.java @@ -0,0 +1,14 @@ +package com.baeldung.loginredirect; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +class LoginRedirectMvcConfig implements WebMvcConfigurer { + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(new LoginPageInterceptor()); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectSecurityConfig.java new file mode 100644 index 0000000000..8bd3200608 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectSecurityConfig.java @@ -0,0 +1,43 @@ +package com.baeldung.loginredirect; + +import org.springframework.context.annotation.Bean; +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.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@Configuration +@EnableWebSecurity +class LoginRedirectSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("user").password(encoder().encode("user")).roles("USER"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + + http + .addFilterAfter(new LoginPageFilter(), UsernamePasswordAuthenticationFilter.class) + + .authorizeRequests() + .antMatchers("/loginUser").permitAll() + .antMatchers("/user*").hasRole("USER") + + .and().formLogin().loginPage("/loginUser").loginProcessingUrl("/user_login") + .failureUrl("/loginUser?error=loginError").defaultSuccessUrl("/userMainPage").permitAll() + + .and().logout().logoutUrl("/user_logout").logoutSuccessUrl("/loginUser").deleteCookies("JSESSIONID") + .and().csrf().disable(); + } + + @Bean + public static PasswordEncoder encoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/UsersController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/UsersController.java new file mode 100644 index 0000000000..cfe87d9c21 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/UsersController.java @@ -0,0 +1,32 @@ +package com.baeldung.loginredirect; + +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +class UsersController { + + @GetMapping("/userMainPage") + public String getUserPage() { + return "userMainPage"; + } + + @GetMapping("/loginUser") + public String getUserLoginPage() { + if (isAuthenticated()) { + return "redirect:userMainPage"; + } + return "loginUser"; + } + + private boolean isAuthenticated() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null || authentication instanceof AnonymousAuthenticationToken) { + return false; + } + return authentication.isAuthenticated(); + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/spring-security-login-redirect.xml b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/spring-security-login-redirect.xml new file mode 100644 index 0000000000..e711abce1f --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/spring-security-login-redirect.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/userMainPage.html b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/userMainPage.html new file mode 100644 index 0000000000..501d019790 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/templates/userMainPage.html @@ -0,0 +1,10 @@ + + + + +Baeldung Login Redirect + + +Welcome user! Logout + + \ No newline at end of file From ec6e0cf7890c9658f3994588a16c4261c6172b9f Mon Sep 17 00:00:00 2001 From: Cicio Flaviu Date: Mon, 15 Jun 2020 10:06:37 +0300 Subject: [PATCH 2/2] BAEL-4018 Improved login redirect classes. --- .../baeldung/loginredirect/LoginPageFilter.java | 16 ++++++++++------ .../loginredirect/LoginPageInterceptor.java | 4 ++-- .../loginredirect/LoginRedirectApplication.java | 3 ++- .../baeldung/loginredirect/UsersController.java | 2 +- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageFilter.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageFilter.java index 635f811e7a..3c6d076756 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageFilter.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageFilter.java @@ -18,20 +18,24 @@ class LoginPageFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - if (isAuthenticated() && ((HttpServletRequest) request).getRequestURI().equals("/loginUser")) { + HttpServletRequest servletRequest = (HttpServletRequest) request; + HttpServletResponse servletResponse = (HttpServletResponse) response; + + if (isAuthenticated() && "/loginUser".equals(servletRequest.getRequestURI())) { String encodedRedirectURL = ((HttpServletResponse) response).encodeRedirectURL( - ((HttpServletRequest) request).getContextPath() + "/userMainPage"); + servletRequest.getContextPath() + "/userMainPage"); - ((HttpServletResponse) response).setStatus(HttpStatus.SC_TEMPORARY_REDIRECT); - ((HttpServletResponse) response).setHeader("Location", encodedRedirectURL); + servletResponse.setStatus(HttpStatus.SC_TEMPORARY_REDIRECT); + servletResponse.setHeader("Location", encodedRedirectURL); } - chain.doFilter(request, response); + + chain.doFilter(servletRequest, servletResponse); } private boolean isAuthenticated() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null || authentication instanceof AnonymousAuthenticationToken) { + if (authentication == null || AnonymousAuthenticationToken.class.isAssignableFrom(authentication.getClass())) { return false; } return authentication.isAuthenticated(); diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageInterceptor.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageInterceptor.java index f8fbe76b61..aa93201f37 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageInterceptor.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginPageInterceptor.java @@ -16,7 +16,7 @@ class LoginPageInterceptor extends HandlerInterceptorAdapter { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { UrlPathHelper urlPathHelper = new UrlPathHelper(); - if (urlPathHelper.getLookupPathForRequest(request).equals("/loginUser") && isAuthenticated()) { + if ("/loginUser".equals(urlPathHelper.getLookupPathForRequest(request)) && isAuthenticated()) { String encodedRedirectURL = response.encodeRedirectURL( request.getContextPath() + "/userMainPage"); @@ -31,7 +31,7 @@ class LoginPageInterceptor extends HandlerInterceptorAdapter { private boolean isAuthenticated() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null || authentication instanceof AnonymousAuthenticationToken) { + if (authentication == null || AnonymousAuthenticationToken.class.isAssignableFrom(authentication.getClass())) { return false; } return authentication.isAuthenticated(); diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectApplication.java index b7f9863775..1e44240449 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectApplication.java @@ -2,9 +2,10 @@ package com.baeldung.loginredirect; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ImportResource; @SpringBootApplication -//@ImportResource({"classpath*:spring-security-login-redirect.xml"}) +@ImportResource({"classpath*:spring-security-login-redirect.xml"}) class LoginRedirectApplication { public static void main(String[] args) { SpringApplication.run(LoginRedirectApplication.class, args); diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/UsersController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/UsersController.java index cfe87d9c21..308495d2ab 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/UsersController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/loginredirect/UsersController.java @@ -24,7 +24,7 @@ class UsersController { private boolean isAuthenticated() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null || authentication instanceof AnonymousAuthenticationToken) { + if (authentication == null || AnonymousAuthenticationToken.class.isAssignableFrom(authentication.getClass())) { return false; } return authentication.isAuthenticated();