Cover Image for Spring Login Example
187 views

Spring Login Example

The simple example of how to implement a login functionality using Spring Boot and Thymeleaf. In this example, we’ll create a basic login form that allows users to log in with a username and password.

1. Create a Spring Boot Project:

Start by creating a new Spring Boot project using Spring Initializr or your preferred development environment.

2. Create an Entity:

Create a simple User entity to represent user data. For this example, we’ll use in-memory users.

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;

    // Getters and setters
}

3. Create a Repository:

Create a repository interface for the User entity.

public interface UserRepository extends JpaRepository<User, Long> {
    User findByUsername(String username);
}

4. Create a Login Controller:

Create a controller that handles the login process.

@Controller
public class LoginController {

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

5. Create Login Form:

Create a Thymeleaf template for the login form.

src/main/resources/templates/login.html:

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

6. Configure Spring Security:

In your Spring Security configuration class, you can set up the login process.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserRepository userRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/dashboard")
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(username -> {
            User user = userRepository.findByUsername(username);
            if (user != null) {
                return new org.springframework.security.core.userdetails.User(
                        user.getUsername(), user.getPassword(), Collections.emptyList());
            } else {
                throw new UsernameNotFoundException("User not found");
            }
        });
    }
}

7. Create a Dashboard Controller:

Create a controller for the dashboard page after successful login.

@Controller
public class DashboardController {

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

8. Create Dashboard Template:

Create a simple dashboard template.

src/main/resources/templates/dashboard.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
</head>
<body>
    <h2>Welcome to the Dashboard</h2>
    <p>You are now logged in.</p>
</body>
</html>

9. Run the Application:

Run your Spring Boot application and navigate to http://localhost:8080/login to see the login form. You can then log in with the username and password you’ve set up.

Remember that this example is basic and doesn’t include features like password encryption, user roles, and proper error handling. For a production environment, you should consider using a more secure and sophisticated authentication system.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS