Cover Image for Spring Login & Logout Example
181 views

Spring Login & Logout Example

The example of how to implement a basic login and logout functionality using Spring Security in a Spring Boot application. This example will show you how to set up a login form, configure authentication, and provide logout functionality.

1. Create a Spring Boot Project:

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

2. Configure Spring Security:

In your Spring Boot project, configure Spring Security by creating a security configuration class that extends WebSecurityConfigurerAdapter.

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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll() // Public resources
                .anyRequest().authenticated() // Require authentication for other requests
                .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/dashboard")
                .permitAll()
                .and()
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login?logout")
                .permitAll();
    }

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

3. Create Login and Logout Pages:

Create Thymeleaf templates for login and logout pages:

  • src/main/resources/templates/login.html
  • src/main/resources/templates/dashboard.html

4. Implement User Details Service:

Implement a user details service that retrieves user information from a database or other sources. In this example, we’ll use an in-memory user.

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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // ... previous configuration ...

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder passwordEncoder = passwordEncoder();
        auth
            .inMemoryAuthentication()
                .withUser("user")
                    .password(passwordEncoder.encode("password"))
                    .roles("USER");
    }
}

5. Create Controllers:

Create controllers for login, logout, and dashboard.

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

@Controller
public class AuthController {

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

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

6. Run the Application:

Run your Spring Boot application. You should be able to access the login page at http://localhost:8080/login and the dashboard after successful login.

Remember that this is a basic example, and you can customize and expand it to fit your specific requirements. For production use, consider using a more sophisticated user management system and security configurations.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS