Spring Security is a framework what spring calls it. It provides authentication, authorization, and protection against attacks. It has become kind of a standard for securing spring based applications.
In this tutorial we will learn about spring security with spring boot and its example.
Spring Security requires a Java 8 or higher Run-time Environment.
Spring security Features
- Authentication
- Authorization
- Protection against common exploits
1. Authentication
There are many ways to authenticate users, like the most common way is by requiring user to enter username and password. There are many Password Storage Techniques like.
Using Spring Security PasswordEncoder.
Using BCryptPasswordEncoder.
Using DelegatingPasswordEncoder.
Using NoOpPasswordEncoder.
2. Protection against common exploits
Spring Security provides protection against common exploits. Whenever possible, the protection is enabled by default.
CSRF (Cross Site Request Forgery) Attacks
Default Security Http Headers.
Example : Default Security HTTP Response Headers
Cache-Control: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache Expires: 0 X-Content-Type-Options: nosniff Strict-Transport-Security: max-age=31536000 ; includeSubDomains X-Frame-Options: DENY X-XSS-Protection: 1; mode=bloc
3. Http
As a framework, Spring Security does not handle HTTP connections and thus does not provide support for HTTPS directly. However, it does provide a number of features that help with HTTPS usage, like.
Redirect to HTTPS
Strict Transport Security
Proxy Server Configuration
Spring Security with Spring Boot Example
1. Project Structure

2. REST Controller – EmployeeController
First creating a REST controller class like this, with few HTTP methods like GET, POST, DELETE.
package com.programmertoday.springsecurity.controller;
import com.programmertoday.springsecurity.model.Employee;
import com.programmertoday.springsecurity.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("api")
public class EmployeeController {
@Autowired
EmployeeService empService;
// Get all Employees
@GetMapping("/employees")
List<Employee> findAll() {
return empService.findAll();
}
// Save Employees
@PostMapping("/employees")
@ResponseStatus(HttpStatus.CREATED)
String newEmployee(@RequestBody Employee newEmployee) {
empService.save(newEmployee);
return "Success fully created Employees";
}
// Delete Employees with id
@DeleteMapping("/employees/{id}")
String deleteBook(@PathVariable Integer id) {
empService.deleteEmpById(id);
return "deleted employee with id " +id + " successfully";
}
}
3. Model Class – Employee
package com.programmertoday.springsecurity.model;
public class Employee {
private int empId;
private String empName;
private String empDept;
private String empLocation;
public Employee(int empId, String empName,
String empDept, String empLocation) {
this.empId = empId;
this.empName = empName;
this.empDept = empDept;
this.empLocation = empLocation;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpDept() {
return empDept;
}
public void setEmpDept(String empDept) {
this.empDept = empDept;
}
public String getEmpLocation() {
return empLocation;
}
public void setEmpLocation(String empLocation) {
this.empLocation = empLocation;
}
}
4. Service class – EmployeeService
package com.programmertoday.springsecurity.service;
import com.programmertoday.springsecurity.model.Employee;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class EmployeeService {
public List<Employee> findAll() {
List<Employee> empList = new ArrayList<>();
empList.add(new Employee(101,"Maverick","RE","SF"));
empList.add(new Employee(102,"John","CS","NJ"));
empList.add(new Employee(103,"Drake","HE","NYC"));
return empList;
}
public void save(Employee newEmployee) {
System.out.println("saving new employee");
// .. add your own code, it's just for basic understanding
}
public void deleteEmpById(Integer id) {
// .. add your own code, it's just for basic understanding
System.out.println("Employee with "+id+" is deleted");
}
}
5. Config class – SpringSecurityConfig
package com.programmertoday.springsecurity.configs;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.WebSecurityConfigurerAdapter;
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
// Creating just 2 users for demonstration
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}password").roles("USER", "ADMIN");
}
// Securing the endpoints with HTTP Basic authentication
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//HTTP Basic authentication
.httpBasic()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/employees/**").hasRole("USER")
.antMatchers(HttpMethod.POST, "/api/employees").hasRole("ADMIN")
.antMatchers(HttpMethod.DELETE, "/api/employees/**").hasRole("ADMIN")
.and()
.csrf().disable()
.formLogin();//.disable();
}
}
6. SpringBootApplication – SpringSecurityApplication Class
Now run the application.
package com.programmertoday.springsecurity;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class, args);
}
}
OUTPUT
Example 1 : Unauthorized Login Unsuccessful because of Spring Security
// With a different user(user123) who is not an authorized user
C:\>curl localhost:8080/api/employees -u user123:password
{“timestamp”:”2020-04-05T14:39:25.805+0000″,”status”:401,”error”:”Unauthorized”,”message”:”Unauthorized”,”path”:”/api/employees”}
// Calling Delete API with a user who is not authorized to access Delete API
C:\>curl -X DELETE localhost:8080/api/employees/1 -u user:password
{“timestamp”:”2020-04-05T14:37:23.688+0000″,”status”:403,”error”:”Forbidden”,”message”:”Forbidden”,”path”:”/api/employees/1″}
Example 2 : Successful Login
GET API : with user=user and password=password
C:\>curl localhost:8080/api/employees -u user:password
[{“empId”:101,”empName”:”Maverick”,”empDept”:”IT”,”empLocation”:”SF”},{“empId”:102,”empName”:”John”,”empDept”:”CS”,”empLocation”:”NJ”},{“empId”:103,”empName”:”Drake”,”empDept”:”HE”,”empLocation”:”NYC”}]
DELETE API Call : with user=admin and password=password
C:\> curl -X DELETE localhost:8080/api/employees/1 -u admin:password
deleted employee with id 1 successfully
Try testing in Browser as well
Open the browser : localhost:8080/api/employees – it will redirect to /login first
Provide the right credentials as configured in the SpringSecurityConfig class


Summary
In this tutorial we learnt how to use spring security with REST APIs and spring boot. We created a spring boot REST based simple project and secured it using spring security. At the end we also saw the output of the code using curl command lines as well as in the browser.
Please comment below for suggestions and questions, I hope you liked it !





