Redirect to Different Pages After Login With Spring Security

In many web applications, user are redirected to the different pages after logging in based on their roles or other arrtributes. For example, an admin user might be the redirected to the admin dashboard while the regular user might be taken to the home page. Spring Security can provides the flexible way to the handle these redirections and it can allowing you to create the more personalized user experience. This article will guide you through the steps to configure the role based redirection after login in the Spring Security project.

The main concept of the redirecting the users to different pages after login with Spring Security involves the customizing the authentication success handling process. It can allows you to direct the users to specific pages based on their roles or other attributes after they successfully login in. This customization can achieved by implementing the custom authentication success handler and configuring it in the Spring Security setup.

Implementation to Redirect to Different Pages After Login With Spring Security

Below are the implementation steps to redirect to different pages after login with spring.

Step 1: Create a new Spring Boot project using Spring Initializr and include the required dependencies as mentioned below:

  • Spring Web
  • Spring Security
  • Lombok
  • Spring DevTools
  • Thymeleaf

After the project creation done, the folder structure will be like the below image:


Step 2: Open the application.properties file and add the configuration for the security username and password of the user and admin, database, thymeleaf of the Spring Security application in the project.

spring.application.name=spring-security-redirect-pages


spring.datasource.url=jdbc:mysql://localhost:3306/example
spring.datasource.username=root
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

#user credentials
spring.security.user.name=user
spring.security.user.password=password
spring.security.user.roles=USER

#admin credentials
spring.security.admin.name=admin
spring.security.admin.password=password
spring.security.admin.roles=ADMIN


Step 3: Create a new package named config and in that package, create a new Java class named SecurityConfig.

Go to src > org.example.springsecurityredirectpages > config > SecurityConfig and put the below code.

Java
package org.example.springsecurityredirectpages.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .requestMatchers("/user/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .successHandler(customSuccessHandler())
                .permitAll()
                .and()
                .logout()
                .permitAll();
        return http.build();
    }

    @Bean
    public AuthenticationSuccessHandler customSuccessHandler() {
        return new CustomAuthenticationSuccessHandler();
    }
}


Step 4: Create a new package named config and in that package, create a new Java class named CustomAuthenticationSuccessHandler.

Go to src > org.example.springsecurityredirectpages > config > CustomAuthenticationSuccessHandler and put the below code.

Java
package org.example.springsecurityredirectpages.config;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String redirectURL = request.getContextPath();

        if (authentication.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))) {
            redirectURL = "/admin/home";
        } else if (authentication.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_USER"))) {
            redirectURL = "/user/home";
        }

        response.sendRedirect(redirectURL);
    }
}


Step 5: Create a new package named controller and in that package, create a new Java class named AdminController.

Go to src > org.example.springsecurityredirectpages > controller > AdminController and put the below code.

Java
package org.example.springsecurityredirectpages.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class AdminController {

    @GetMapping("/admin/home")
    public String adminHome() {
        return "adminHome";
    }
}


Step 6: Create a new package named controller and in that package, create a new Java class named UserController.

Go to src > org.example.springsecurityredirectpages > controller > UserController and put the below code.

Java
package org.example.springsecurityredirectpages.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserController {

    @GetMapping("/user/home")
    public String userHome() {
        return "userHome";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }
}


Step 7: Open the main class and write the below code. (No change are required)

Java
package org.example.springsecurityredirectpages;

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

@SpringBootApplication
public class SpringSecurityRedirectPagesApplication {

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

}


Step 8: Create the Login HTML page.

Go to src > main > resources > templates > login.html and put the below code.

HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Login</title>
</head>
<body>
<form th:action="@{/login}" method="post">
    <div>
        <label>Username:</label>
        <input type="text" name="username" />
    </div>
    <div>
        <label>Password:</label>
        <input type="password" name="password" />
    </div>
    <div>
        <button type="submit">Login</button>
    </div>
</form>
</body>
</html>


Step 9: Create the UserHome HTML page.

Go to src > main > resources > templates > userHome.html and put the below code.

HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User Home</title>
</head>
<body>
<h1>Welcome User!</h1>
</body>
</html>


Step 10: Create the AdminHome HTML page

Go to src > main > resources > templates > adminHome.html and put the below code.

HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Admin Home</title>
</head>
<body>
<h1>Welcome Admin!</h1>
</body>
</html>


pom.xml:

XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.example</groupId>
    <artifactId>spring-security-redirect-pages</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-security-redirect-pages</name>
    <description>spring-security-redirect-pages</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity6</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


Step 11: After completing the project, it will start at port 8080.


Login page:

API:

http://localhost:8080/login

If we enter the user credential the it redirects to the user home page.

  • username: user
  • password: password

If we enter the admin credential the it redirects to the user home page.

  • username: admin
  • password: password

Output:


AdminHome page:


UserHome page:

After hitting the URL, the below page will redirect.

This project demonstrates that how to Redirect users to different pages after the login based on their roles enhances the user experience.



Contact Us