Open In App

Spring Security – Get the Current Logged in User Details with Database

Last Updated : 17 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Many times there is a requirement to get the currently logged-in user details so that we can display the user details in our view. So in this article, we will discuss how to retrieve the currently logged-in user details in Spring Security. We’re going to build on top of the simple Spring MVC example and Get the Current Logged in User Details with the Database. So in brief we can perform the task with the help of the Authentication class. A sample code is given below.

// Principal means username
@GetMapping("/")
public String helloGfg(Principal principal, Authentication auth, Model model) {
// Get the Username
String userName = principal.getName();
System.out.println("Current Logged in User is: " + userName);
// Get the User Roles/Authorities
Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
System.out.println("Current Logged in User Roles are: " + authorities);

model.addAttribute("username", userName);
model.addAttribute("roles", authorities);

return "home-page";
}

Note: We are going to use the MySQL database to fetch the User Details in this article.

Example Project

Step 1: Create Your Project and Configure Apache Tomcat Server

Note: We are going to use Spring Tool Suite 4 IDE for this project. Please refer to this article to install STS in your local machine How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE.

Step 2: Create Schema and Tables in MySQL Workbench and Put Some Sample Data

Go to your MySQL Workbench and create a schema named gfgspringsecuritydemo and inside that create two tables users and authorities and put some sample data as shown in the below image.

Note: It is strictly recommended that (recommended by spring official docs) you should create the tables as per the schema. The column name must be the same. You may put some sample data or we are going to take the data from the users through the registration form.

users Table:

Here is the users Table Schema

  1. username varchar_ignorecase(50) not null primary key,
  2. password varchar_ignorecase(50) not null,
  3. enabled boolean not null

Please refer to the below image for reference.

JDBC-Authentication-2.png

authorities Table:

Here is the authorities Table Schema

  • username varchar_ignorecase(50) not null,
  • authority varchar_ignorecase(50) not null,
  • constraint fk_authorities_users foreign key(username) references users(username)

Please refer to the below image for reference.

JDBC-Authentication-3.png

Step 3: Folder Structure

Before moving to the project let’s have a look at the complete project structure for our Spring MVC application.

Step 4: Add Dependencies to pom.xml File

Add the following dependencies to your pom.xml file

  • Spring Web MVC
  • Java Servlet API
  • Spring Security Config
  • Spring Security Web
  • Spring JDBC
  • MySQL Connector Java

XML




<dependencies>
   
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.24</version>
    </dependency>
     
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>   
     
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>5.7.3</version>
    </dependency>
     
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>5.7.3</version>
    </dependency>
   
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.24</version>
    </dependency>
 
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.28</version>
    </dependency>
     
</dependencies>


Below is the complete pom.xml file. Please cross-verify if you have missed some dependencies.

XML




<?xml version="1.0" encoding="UTF-8"?>
 
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.gfg.springsecurity</groupId>
    <artifactId>springsecurity</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
 
    <name>springsecurity Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.gfg.com</url>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
 
    <dependencies>
 
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.24</version>
        </dependency>
 
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.7.3</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.7.3</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.24</version>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
 
 
    </dependencies>
 
    <build>
        <finalName>springsecurity</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven
                defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>


Step 5: Configuring Dispatcher Servlet

Please refer to this article What is Dispatcher Servlet in Spring? and read more about Dispatcher Servlet which is a very very important concept to understand. Now we are going to configure Dispatcher Servlet with our Spring MVC application.

Go to the src > main > java and create a class WebAppInitilizer. Below is the code for the WebAppInitilizer.java file.

File: WebAppInitilizer.java

Java




package com.gfg.config;
 
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
 
public class WebAppInitilizer extends
               AbstractAnnotationConfigDispatcherServletInitializer {
 
    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }
 
    @Override
    protected Class<?>[] getServletConfigClasses() {
        Class[] configFiles = {MyAppConfig.class};
        return configFiles;
    }
 
    @Override
    protected String[] getServletMappings() {
        String[] mappings = {"/"};
        return mappings;
    }
 
}


Create another class in the same location (src > main > java) and name it MyAppConfig. Below is the code for the MyAppConfig.java file.

File: MyAppConfig.java

Java




package com.gfg.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
 
@Configuration
@EnableWebMvc
@ComponentScan("com")
public class MyAppConfig {
 
}


Reference article: Spring – Configure Dispatcher Servlet in Three Different Ways

Step 6: Create Your Spring MVC Controller

Go to the src > main > java and create a class GfgController. Below is the code for the GfgController.java file.

File: GfgController.java

Java




package com.gfg.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
 
@Controller
public class GfgController {
     
    @GetMapping("/")
    public String helloGfg() {
        return "home-page";
    }
   
}


Go to the src > main > java and create a class LoginController. Below is the code for the LoginController.java file.

File: LoginController.java

Java




package com.gfg.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
 
@Controller
public class LoginController {
     
    @GetMapping("/customLogin")
    public String customLogin() {
        return "custom-login";
    }
 
}


Reference article: Create and Run Your First Spring MVC Controller in Eclipse/Spring Tool Suite

Step 7: Create Your Spring MVC View

Go to the src > main > webapp > WEB-INF > right-click > New > Folder and name the folder as views. Then views > right-click > New > JSP File and name your first view. Here we have named it as home-page.jsp file. Below is the code for the home-page.jsp file. We have created a simple web page inside that file.

File: home-page.jsp

HTML




<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored = "false" %>
<!DOCTYPE html>
<html>
<body bgcolor="green">
   
    <h1>Hi ${username} !!</h1>
     
    <form:form action="logout" method="POST">
     
        <input type="submit" value="Logout">
     
    </form:form>
     
     
</body>
</html>


Also, create another view named custom-login.jsp file. Below is the code for the custom-login.jsp file. We have created a simple login form inside that file.

File: custom-login.jsp

HTML




<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<title>GFG Login Page</title>
<body bgcolor="green">
    <h1>Custom Login Page</h1>
     
    <form:form action="process-login" method="POST">
     
        Username : <input type="text" name="username">
        <br/>
        Password : <input type="password" name="password">
        <br/>
        <input type="submit" value="Login">
     
    </form:form>
     
</body>
</html>


Reference articles:

Step 8: Setting Up ViewResolver in Spring MVC

Go to the src > main > java > MyAppConfig and set your ViewResolver like this

File: MyAppConfig.java

Java




package com.gfg.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
 
@Configuration
@EnableWebMvc
@ComponentScan("com")
public class MyAppConfig {
     
    @Bean
    InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
 
}


Reference article: ViewResolver in Spring MVC

Step 9: Setting Up Spring Security Filter Chain

Go to the src > main > java and create a class MySecurityAppConfig and annotate the class with @EnableWebSecurity annotation. This class will help to create the spring security filter chain. Below is the code for the MySecurityAppConfig.java file.

File: MySecurityAppConfig.java

Java




package com.gfg.config;
 
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
 
// This class will help to create
// spring security filter chain
@EnableWebSecurity
public class MySecurityAppConfig extends WebSecurityConfigurerAdapter {
 
}


Step 10: Create Spring Security Initilizer

Go to the src > main > java and create a class SecurityInitializer. This class will help to register the spring security filter chain with our application. Below is the code for the SecurityInitializer.java file.

File: SecurityInitializer.java

Java




package com.gfg.config;
 
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
 
// This class will help to register spring security
// filter chain with our application
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
 
}


Now we are done with setting up our Spring Security Filter Chain.

Step 11: Get the Current Logged in User Details with Database Implementation

Modify the MyAppConfig file. Here we are going to create the DataSource Bean. That means we are going to write the code for the MySQL Database connection.

File: MyAppConfig.java

Java




package com.gfg.config;
 
import javax.sql.DataSource;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
 
@Configuration
@EnableWebMvc
@ComponentScan("com")
public class MyAppConfig {
     
    @Bean
    InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
     
    // Connect to MySQL Database
    @Bean
    DataSource dataSource() {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
         
        driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/gfgspringsecuritydemo");
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("143@Arpilu");
        driverManagerDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
         
        return driverManagerDataSource;
    }
 
}


Modify the MySecurityAppConfig file.

File: MySecurityAppConfig.java

Java




package com.gfg.config;
 
import javax.sql.DataSource;
 
import org.springframework.beans.factory.annotation.Autowired;
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.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
 
// This class will help to create
@SuppressWarnings("deprecation")
// spring security filter chain
@EnableWebSecurity
public class MySecurityAppConfig extends WebSecurityConfigurerAdapter {
     
    @Autowired
    private DataSource datasource;
     
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // load the users info from the database
        // username, password, and role
        auth
        .jdbcAuthentication()
        .dataSource(datasource)
        .passwordEncoder(NoOpPasswordEncoder.getInstance());
    }
     
    // Configuring Form Login through configure method
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeHttpRequests()
        .anyRequest()
        .authenticated()
            .and()
            .formLogin().loginPage("/customLogin").loginProcessingUrl("/process-login").permitAll()
            .and()
            .httpBasic()
            .and()
            .logout().permitAll();
    }
         
}


Modify the GfgController file. Here we are going to write the logic to get the Current Logged in User Details.

File: GfgController.java

Java




package com.gfg.controller;
 
import java.security.Principal;
import java.util.Collection;
 
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
 
@Controller
public class GfgController {
 
    // Principal means username
    @GetMapping("/")
    public String helloGfg(Principal principal, Authentication auth, Model model) {
        // Get the Username
        String userName = principal.getName();
        System.out.println("Current Logged in User is: " + userName);
 
        // Get the User Roles/Authorities
        Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
        System.out.println("Current Logged in User Roles are: " + authorities);
         
        model.addAttribute("username", userName);
        model.addAttribute("roles", authorities);
         
        return "home-page";
    }
 
}


Now, let’s run the application and test it out.

Step 12: Run Your Spring MVC Application

To run our Spring MVC Application right-click on your project > Run As > Run on Server. After that use the following URL to run your controller.

http://localhost:8080/springsecurity/customLogin

And it will ask for authentication to use the endpoint and a pop-up screen will be shown like this.

Spring-Security---Get-The-Current-Logged-in-User-Details-1.png

Now sign in with your database credentials

  • Username: anshul
  • Password: 123

And now you can access your homepage and you can see we get the Current Logged in User Name and display it in a view.

Spring-Security---Get-The-Current-Logged-in-User-Details.png

You can also see we have printed all the details of the user in the console. Refer to the below image.

Spring-Security---Get-The-Current-Logged-in-User-Details-2.png



Similar Reads

Spring - Add User Name and Password in Spring Security
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is fou
3 min read
Spring Boot 3.0 - JWT Authentication with Spring Security using MySQL Database
In Spring Security 5.7.0, the spring team deprecated the WebSecurityConfigurerAdapter, as they encourage users to move towards a component-based security configuration. Spring Boot 3.0 has come with many changes inSpring Security . In this article, we'll learn how to implement JWT authentication and authorization in a Spring Boot 3.0 application us
7 min read
Spring MVC - Get University/College Details via REST API
REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring MVC is a Web MVC Framework for building web applications. It is a spring module same as spring boot, s
6 min read
Spring Security - security none, filters none, access permitAll
In Spring Boot, Spring Security is the most powerful authentication and access control framework for Java applications. Spring Security provides strong security features to protect our web applications from various security threats such as authentication, authorization, session management, and web vulnerabilities. It is highly flexible and easy to
6 min read
How to Change Default User and Password in Spring Security?
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is fou
4 min read
Spring Security - Custom Form Login with Database Authentication
In this article, Spring Security Basic Authentication, we have demonstrated the Basic Authentication using In-Memory Authentication. But what if we are required to authenticate the user from the database? And also what if we are required to login with the custom form? In this article, we will explain how to set up, configure, and customize Custom F
8 min read
Spring - Add Roles in Spring Security
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is fou
4 min read
How to Integrate Keycloak with Spring Boot and Spring Security?
Keycloak is Open Source Identity and Access Management (IAM) solution developed by Red Hat. By using this you can add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users. Keycloak provides user federation, strong authentication, user management, fine-grained authorizatio
2 min read
Authentication and Authorization in Spring Boot 3.0 with Spring Security
In Spring Security 5.7.0, the spring team deprecated the WebSecurityConfigurerAdapter, as they encourage users to move towards a component-based security configuration. Spring Boot 3.0 has come with many changes in Spring Security. So in this article, we will understand how to perform spring security authentication and authorization using spring bo
3 min read
Spring Boot | How to access database using Spring Data JPA
Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot
4 min read
Practice Tags :