Adding Spring Security to a SpringBoot project

Below dependency is required for Spring Security in gradle :

implementation 'org.springframework.boot:spring-boot-starter-security:2.2.4.RELEASE'

Note :

Just by adding the above dependency in your build.gradle file the spring security is activated.

What functionalities are provided by Spring boot starter security ?

  • Add mandatory authentication for URLS
  • Adds login form
  • Handles login error
  • Create a default user and password

You just need to build the project and hit the url “http://localhost:8080/” and you will be automatically redirected to “http://localhost:8080/login” and the screen will look like below.

You can login to the above login page using User id as user “user” and password as the password printed in console while starting the project

You can also specify the login id and password in the application.properties file :

spring.security.user.name=tyson
spring.security.user.password=tyson

Code : build.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.2.5.RELEASE'
    id 'io.spring.dependency-management' version '1.0.7.RELEASE'
}

repositories {
    jcenter()
}

dependencies {
    implementation 'com.google.guava:guava:28.0-jre'
    testImplementation 'junit:junit:4.12'
    implementation 'org.springframework.boot:spring-boot-dependencies:2.0.5.RELEASE'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
	implementation 'org.springframework.boot:spring-boot-starter-security:2.2.4.RELEASE'

    components {
        withModule('org.springframework:spring-beans') {
            allVariants {
                withDependencyConstraints {
                    it.findAll { it.name == 'snakeyaml' }.each { it.version { strictly '1.19' } }
                }
            }
        }
    }
}

task runJar{
	dependsOn 'assemble'
	dependsOn 'jar'
	doLast{
  		javaexec { 
    		main="-jar";
    		args = [
            	"build/libs/"+rootProject.name+".jar"
           	]
		} 
	}
}

App.java

package com.spring.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

Leave a Comment