Spring Boot login example with the database without security

Learning Spring Boot is a great thing. Implementation of login to secure our application without using spring security, here we have demonstrated how is it possible and what are the challenges we have to face without spring security. We will be using the request session to store login details.

You may like    Spring Security registration login example

Here we are taking the H2 database for demonstration use can use any other.

Step 1.  Initialize the project from spring initializr with the following dependencies:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    // https://mvnrepository.com/artifact/com.h2database/h2
    implementation group: 'com.h2database', name: 'h2', version: '1.4.200'

    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

Step 2. Set the application properties

server.port=8888

spring.datasource.url=jdbc:h2:~/test
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.jpa.hibernate.ddl-auto=create
#h2 database is a test database it does not needs any username and password

Step 3. Add a model class User.java

@Entity
public class User implements Serializable {
    @Id
    @GeneratedValue
    private long id;
    private String name;
    @Column(unique = true)
    private String email;    //we are taking email as username for login
    private String password;
 
   public User() {
    }
    public User(String name, String email, String password) {
        this.name = name;
        this.email = email;
        this.password = password;
    }
  
// Getters and Setters .......

}

Step 4. Create a JPA repository interface for saving/retrieving data from the database.

public interface UserRepository extends JpaRepository<User,Long> {
    Optional<User> findByEmail(String email);
}

Step 5. Create a sample user and bootstrap data into the database

You can use this method to bootstrap other static data like a list of countries, states, and districts, etc

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @PostConstruct
    public void bootstrapSampleData(){
          if(userRepository.count()==0){ // if no user peresent in database then
              User sampleUser = new User("Lavkush Verma","lavkushverma332@gmail.com","abcd1234");
              userRepository.save(sampleUser);
          }
    }

}

Step 6. Create a controller to handle requests

@Controller
public class MyController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping(value = {"/", "/login"})  
    public String loginPage() {
        return "index";
    }

    @PostMapping("/login")
    public String login(String username, String password, Model model, HttpServletRequest request) {
        Optional<User> optionalUser = userRepository.findByEmail(username);
        if (optionalUser.isPresent()) {
            User user = optionalUser.get();
            if (user.getPassword().matches(password)) {
                request.getSession().setAttribute("userName", user.getName());
                request.getSession().setAttribute("userEmail", user.getEmail());
                model.addAttribute("msg", "You are successfully logged in");
                return "redirect:/dashboard";
            }
        }
        model.addAttribute("error", "Invalid Credentials !");
        return "redirect:/login?error";
    }

    @RequestMapping("/dashboard")
    public String dashboard(HttpServletRequest request) {
        if(request.getSession().getAttribute("userEmail")!=null){
            return "dashboard";
        }else{
            return "redirect:/login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        request.getSession().invalidate();
        return "redirect:/login?logout";
    }
}

Step 7. Now create the login page index.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Login without Spring Security</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--using bootstrap CDN for UI-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <br>
    <br>
    <div class="row">
        <div class="col-md-4"></div>
        <div class="col-md-4">
            <h1 class="text-center">Login Page</h1>
            <div th:if="${param.error}" class="alert alert-danger">
                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                <strong>Failed!</strong> &nbsp;&nbsp;<span>Invalid credentials.</span>
            </div>
            <div th:if="${param.logout}" class="alert alert-success">
                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                <strong>Success!</strong> &nbsp;&nbsp;<span>You logged out successfully.</span>
            </div>
            <form action="/login" method="post" class="needs-validation" novalidate>
                <div class="form-group">
                    <label for="uname" >Username</label>
                    <input type="text" class="form-control" id="uname" placeholder="Enter username" name="username"
                           required>
                    <div class="valid-feedback"></div>
                    <div class="invalid-feedback">Please fill out this field.</div>
                </div>
                <div class="form-group">
                    <label for="pwd">Password</label>
                    <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="password"
                           required>
                    <div class="valid-feedback"></div>
                    <div class="invalid-feedback">Please fill out this field.</div>
                </div>
                <div class="row">
                    <div class="col-md-4"></div>
                    <div class="col-md-4">
                        <button type="submit" class="btn btn-primary">Sign In</button>
                    </div>
                    <div class="col-md-4"></div>
                </div>
            </form>
        </div>
        <div class="col-md-4"></div>
    </div>
</div>

<script>
    // Disable form submissions if there are invalid fields
    (function () {
        'use strict';
        window.addEventListener('load', function () {
            // Get the forms we want to add validation styles to
            var forms = document.getElementsByClassName('needs-validation');
            // Loop over them and prevent submission
            var validation = Array.prototype.filter.call(forms, function (form) {
                form.addEventListener('submit', function (event) {
                    if (form.checkValidity() === false) {
                        event.preventDefault();
                        event.stopPropagation();
                    }
                    form.classList.add('was-validated');
                }, false);
            });
        }, false);
    })();
</script>

</body>
</html>

Step 8. Now create the dashboard.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Login without Spring Security</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <h1 class="text-center text-success">Welcome to dashboard</h1>
    <h3>Hello <span th:text="${#session.getAttribute('userName')}"></span></h3>
    <h4>you email id is <span th:text="${#session.getAttribute('userEmail')}"></span></h4>
    <a href="/logout">Logout</a>
</div>
</body>
</html>

Now you are done. Here are the screens

 
login_without_spring_security

 

 
login_without_spring_security_dashboard_Img

 

Problems that you can face

  •  We need to check the session in every controller which needs a login
  • we need to write redirect code if the user not logged in
  • Increases number of lines of code in every controller
  • Low standard code

Note: If you are using spring boot you must use spring security for authentication and authorization. You must learn it, go to https://easytutorials.live/howto/how-to-implement-spring-security

Thanks for reading this article.



×