Blog Detail

  • Home
  • Create custom login page for Spring Security

Create custom login page for Spring Security

In this post I posted the sample code for create and showing the custom login page instead of spring security default login page. In https://samplecoder.com/spring-security-in-memory-authentication-sample-code/ this post I showed the default spring login page. You just follow the below steps to show the custom login page. First you have to design the your own login page using html and css. And you should enable the spring MVC. Please refer below link to know, how to enable MVC in Spring Boot Application.

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

Login
Login Error
Login Success
Login Success Page

1 Comment

Write a comment