Spring Boot Security Keep Track of Login
Spring Boot Form Security Login Example
In a previous post we had developed a Spring Boot Security Hello World Application
It used http basic security. Besides being not visually helpful it also has some other drawbacks like once logged in, then to log out user has to close the browser.
In this example we make use of the login form provided by Spring Security for authenticating users. We will be adding the security to the Spring Boot Form Handling Example we had created before.
Spring Boot Security - Table Of Contents
Spring Boot + Simple Security Configuration Spring Boot Form Security Login Hello World Example Spring Boot Security - Custom Login Page Example Spring Boot Security - Database Authentication using JDBC Spring Boot Security - Creating Users Programmatically Using JdbcUserDetailsManager Spring Boot Security - Password Encoding Using Bcrypt Spring Boot Security - Enabling CSRF Protection Spring Boot Security - Authentication Handler Example Spring Boot Security - Introduction to OAuth Spring Boot OAuth2 Part 1 - Getting The Authorization Code Spring Boot OAuth2 Part 2 - Getting The Access Token And Using it to Fetch Data.
Video
This tutorial is explained in the below Youtube Video.
Lets Begin-
Maven Project will be as follows-
In the Maven we need to add the spring boot security dependency to the existing dependencies.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javainuse</groupId> <artifactId>boot-form-handling</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>boot-form-handling</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> <version>5.1.21</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Next we configure the Spring Security. In the configuration we specify which urls are to be intercepted, and are to be accessed by which users and having which roles. Next we create users along with passwords and specify them a role.
We will be creating two logins
Username | Role | Pages Accessible | Pages not Accessible |
---|---|---|---|
javainuse | USER ADMIN | Welcome page Show All Employees Page Add Employee | None |
employee | USER | Welcome page Show All Employees Page | Add Employee |
package com.javainuse.config; import org.springframework.beans.factory.annotation.Autowired; 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.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class EmployeeSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/resources/**"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/welcome") .hasAnyRole("USER", "ADMIN").antMatchers("/getEmployees").hasAnyRole("USER", "ADMIN") .antMatchers("/addNewEmployee").hasAnyRole("ADMIN").anyRequest().authenticated().and().formLogin() .permitAll().and().logout().permitAll(); http.csrf().disable(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception { authenticationMgr.inMemoryAuthentication().withUser("employee").password("employee") .authorities("ROLE_USER").and().withUser("javainuse").password("javainuse") .authorities("ROLE_USER", "ROLE_ADMIN"); } }
These are the only java changes required.
The other change is on the JSP side. Spring Security provides a default login and a logout page. The login page will be called automatically when spring intercepts any url which is authenticated. We add code to the menu.jsp to add the logout submenu which ends the user session and logs him out.
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <div style="border: 1px solid #ccc; padding: 5px; margin-bottom: 20px;"> <a href="/welcome">Home</a> | <a href="/addNewEmployee">Add Employee</a> | <a href="/getEmployees">Show Employees</a> | <u><h2 style="color: red;"> <a onclick="document.forms['logoutForm'].submit()">Logout</a> </h3></u> <form id="logoutForm" method="POST" action="/logout"> </form> </div>
© Copyright JavaInUse. All Rights Reserved. Privacy Policy
Spring Boot Security Keep Track of Login
Source: https://www.javainuse.com/spring/boot_form_security