How to get user's name and password in Spring Boot using Spring Security

problem

A user has been logged in to your website and you wish to get their username and password, e.g. for updating it. In this post we will see how to do that.

SOLUTION

Let’s first create a sample Login/ logout application using Spring Initializer

Selecting the following dependencies:

  • Spring Web
  • Spring Security

For language, I chose Java 25, Maven project build tool

spring initializer for login project

Click Generate!

Unzip and open  the project in your IDE, (e.g. IntelliJ)

Open LoginApplication.java which is the main class, Let’s make it a @RestController so it accepts Http requests and responds with simple text.

Also, let’s add an endpoint with @GetMapping to simply say hello world when we visit http://localhost:8080 

Because, Spring Security is on the classpath, by default is enabled and there is a default login page when we open http://localhost:8080 

default Login page spring security

The default user is user

The password is auto generated every time we run the application and it appears in the console’s log as follows:

Spring security auto-generated password in console log

After successful log in, it redirects to http://localhost:8080/?continue and the browser responds with the “Hello World!” text as shown below:

Hello World spring security after login redirect

This web application is quite simple due to the learning purposes.

Logout

We can simply logout by visiting http://localhost:8080/logout and confirm logout as follows:

Logout confirmation Spring security default
Getting details from the logged in user

Now, let’s add another endpoint at /details that will return the current user’s details. In particular the following:

  1. Username
  2. Password
  3. Authorities
LoginApplication.java
				
					@GetMapping("/details")
public String details(Authentication authentication) {
   String username = authentication.getName();

   String password = "";

   if(authentication.getCredentials()!=null) {
       password = authentication.getCredentials().toString();
   }

   String authorities = authentication.getAuthorities().toString();

   return "Username: '" + username+ "'\nPassword: '" + password + "'\nAuthorities: '"+ authorities + "'";
}

				
			

If we rerun the application, visit: http://localhost:8080/details and login we should see the following details:

Logged in users details example with empty password

But the password is empty.

adding users

Instead of using the default user and its auto-generated password, we can specify our own username and password and store it in memory. It could have also been stored in a database but for simplicity we will use the in-memory approach.

Let’s create a Configuration class, and specify the UserDetails bean. 

For example:

LoginApplication.java
				
					package com.programmerabroad.login;


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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.UserDetailsManager;


@Configuration
public class Config {

   @Bean
   public UserDetailsManager users() {

       UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
       UserDetails user = User.builder()
               .username("programmerabroad")
               .password(encoder().encode("password"))
               .build();
       userDetailsManager.createUser(user);

       return userDetailsManager;
   }

   @Bean
   public BCryptPasswordEncoder encoder() {
       return new BCryptPasswordEncoder();
   }
}

				
			

In the code above, in the users() method we’re creating a user object that will have 

  • Username: programmerabroad
  • Password: password

And pass it to the userDetailsManager that creates it in the memory.

Also, in the encoder() method we specify the BCryptPasswordEncoder bean to encode passwords.

running

Start server and visit: http://localhost:8080/details

Signing in with our custom user - spring security example

Click Sign in and you should see the following:

details of custom user - spring security empty password
output

Bear in mind that the password is still empty. We can disable the password from being erased by changing the behaviour of the AuthenticationManagerBuilder.

We can simply pass it as a parameter to our users() method as follows:

LoginApplication.java
				
					@Bean
public UserDetailsManager users(AuthenticationManagerBuilder authenticationManager)	

				
			

Spring will autowire it as it’s already used in the container.

Next, let’s disable the erasure of credentials as follows:

LoginApplication.java
				
					authenticationManager.eraseCredentials(false);

				
			

The complete code:

LoginApplication.java
				
					​​package com.programmerabroad.login;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.UserDetailsManager;


@Configuration
public class Config {

   @Bean
   public UserDetailsManager users(AuthenticationManagerBuilder authenticationManager) {
   
       authenticationManager.eraseCredentials(false);
       
       UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();

       UserDetails user = User.builder()
               .username("programmerabroad")
               .password(encoder().encode("password"))
               .build();

       userDetailsManager.createUser(user);

       return userDetailsManager;
   }

   @Bean
   public BCryptPasswordEncoder encoder() {
       return new BCryptPasswordEncoder();
   }
}

				
			
running

Visit, http://localhost:8080/details and login as before

after disabling password erasure spring security example

Now, we can see the password!

If we wish, we can add some authorities to the user by using the roles() method on the User builder as follows:

LoginApplication.java
				
					UserDetails user = User.builder()
       .username("programmerabroad")
       .password(encoder().encode("password"))
       .roles("USER")
       .build();
				
			
running again

Restart the server and visit: http://localhost:8080/details and login as before

User roles in spring security example

We can now see the user has an authority specified.

changing password

We can change the user’s password by using the UserDetailsManager. In order to do that we will need to autowire it in our main class as follows:

LoginApplication.java
				
					@Autowired
private UserDetailsManager userDetails;
@Autowired
private PasswordEncoder encoder;
				
			

Also, autowired the password encoder because we’re gonna need it for encoding the new password.

Add the endpoint to change password at /change

LoginApplication.java
				
					@GetMapping("/change")
public String changePassword(@RequestParam String newpassword, Authentication authentication) {
   String oldPassword = authentication.getCredentials().toString();
   userDetails.changePassword(oldPassword, encoder.encode(newpassword));
   return "Password changed!";
}

				
			

We can send the new password via a URL parameter, i.e. ?newpassword=[newpassword]

running

Restart the server and visit directly http://localhost:8080/change?newpassword=pass 

(We try to change current password to pass)

It will prompt you to login as before with

  • username: programmerabroad
  • password: password
 

Then, it will display the following:

Password change endpoint spring security example
Logout and try to login with the new password

Visit http://localhost:8080/logout and click log out

Logout confirmation Spring security default
Re Login

Visit: http://localhost:8080/details

Login with the following credentials:

  • Username: programmerabroad
  • Password: pass
LoggedIn user with changed password - spring security

We can see the new password works!

conclusion

In this post we saw how to quickly setup a Spring project with Spring Security that provides out of the box a login and a logout webpage. Then we saw how to create a user in memory with a custom username, password and authorities. On top of that we disabled the password erasure. Finally we saw how to change a password by hitting an endpoint. 

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.