In this post, I have posted the sample code to create a custom login page instead of spring security default login page. In (https://samplecoder.com/spring-security-in-memory-authentication-sample-code/) this post, I have shown the default login page. But in this page I have explained the steps to add your own custom login page.
Why we need to add a custom login page?
The default login page comes with spring security plugin. So it does not have much classic look. When you are developing the any application that should be more classic and more attractive, and same way login page design also should match with the your application theme. That would increase the traffic of your application. Spring security allows you to add your own custom login page for form based authentication.
How to create a custom login page?
Create a custom login page is not a big task. Just follow the below steps to add the custom login page. First, you have to design the your own login page using HTML and CSS. And then enable the MVC architecture. If you don’t know, that how to enable MVC, please refer below link to know that. https://samplecoder.com/enable-mvc-in-spring-boot/
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- For MVC - Start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- For MVC - End -->
SystemUser.java
package com.samplecoder.emo.entity;
public class SystemUser {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
SecurityConfiguration.java
package com.samplecoder.emo.config;
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.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 SecurityConfiguration extends WebSecurityConfigurerAdapter{
@Bean
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("$2a$10$7F3YaFnsPQIjbeVLvarwqe3/J6Gdn.fSCpPbhYfzNhuAb/fFo6xxa").roles("ADMIN");
auth.inMemoryAuthentication().withUser("user1").password("$2a$10$uXzJvWQoZORrajgTOAKdeu0SOFJs46pS/TGB3MpCPwATaXLAheOU2").roles("USER");
auth.inMemoryAuthentication().withUser("user2").password("$2a$10$Wd9y/A2dFSLmkbQB.3g5iuoSrKcAHKJnpU8zuC61LkvwJAinYlGmK").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
http.authorizeRequests()
.antMatchers("/loginPage","/authenticate").permitAll()
.anyRequest().authenticated()
.and().formLogin()
.loginProcessingUrl("/authenticate").usernameParameter("username").passwordParameter("password")
.loginPage("/loginPage")
.failureForwardUrl("/loginPage?error=Y")
.defaultSuccessUrl("/index", true)
.and().sessionManagement().sessionFixation().migrateSession();
}
}
application.properties
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
ApplicationController.java
package com.samplecoder.emo.controller;
import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.samplecoder.emo.entity.SystemUser;
@Controller
public class ApplicationController {
@GetMapping("/index")
public ModelAndView index(Authentication auth) {
ModelAndView modelAndView = new ModelAndView("index");
modelAndView.addObject("user", auth.getUsername());
return modelAndView;
}
@RequestMapping(value = {"/loginPage"})
public ModelAndView loginPage(@RequestParam(name = "error", defaultValue = "N") String error,
@ModelAttribute("user") SystemUser user) {
ModelAndView modelAndView = new ModelAndView("loginpage");
user = user != null ? user : new SystemUser();
modelAndView.addObject("user", user);
modelAndView.addObject("error", error);
return modelAndView;
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring Login</title>
<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="d-flex justify-content-center">
<div class="col-lg-6 card">
<div class="card-body">
<h1>Hello <c:out value="${user}"/>!. This is my spring boot MVC application</h1>
<a href="/logout" class="btn btn-danger">Logout</a>
</div>
</div>
</div>
</body>
</html>
loginPage.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring Login</title>
<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="d-flex justify-content-center">
<div class="col-lg-4 card">
<div class="card-body">
<h1 class="card-title">Login Here...</h1>
<c:if test="${error == 'Y'}">
<div class="alert alert-danger" role="alert">
Invalid username or password!.
</div>
</c:if>
<form:form action="/authenticate" method="post" class="col-lg-12" modelAttribute="user">
<div class="form-group">
<label>Username</label>
<form:input name="username" path="username" class="form-control"/>
</div>
<div class="form-group">
<label>Password</label>
<form:input type="password" name="password" path="password" class="form-control"/>
</div>
<div class="col-lg-12 text-right">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form:form>
</div>
</div>
</div>
</body>
</html>
Result: http://localhost:8080/loginPage



One Comment on “Create a custom login page”
Comments are closed.