In this tutorials, I am going to show how to secure spring boot rest endpoints using Spring Boot in memory basic authentication.

Spring Boot In Memory Basic Authentication:

As part of this tutorials, I am going to create a simple spring boot rest service which provides 3 basic endpoints such as reading, creating and deleting Items and these 3 endpoints have to be secured.

Spring Boot In Memory Basic Authentication Example:

Here, I am going to create a 2 different roles ADMIN and USER.

The users which are having ADMIN role can be accessible to Create and Delete Items. The USER role can be accessible to reading Items.

Technologies Used:

  • Spring Boot 2.0.5
  • Spring Boot Security
  • Java 8
  • Maven

Application Structure:

Spring Boot In Memory Basic Authentication Example

Project Dependencies:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""


  <description>Spring Boot In Memory Basic Authentication Security</description>

    <relativePath/> <!-- lookup parent from repository -->





Security Configuration.

Creating 2 users: chandra and admin using Spring Boot’s in-memory AuthenticationManagerBuilder and assigned roles with USER and ADMIN respectively.
package com.onlinetutorialspoint.config;

import org.springframework.context.annotation.Configuration;

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(AuthenticationManagerBuilder managerBuilder) throws Exception{

    protected void configure(HttpSecurity httpSecurity) throws Exception {

Creating Item Model
package com.onlinetutorialspoint.model;


public class Item implements Serializable {
    private Integer id;
    private String name;
    private String category;

    public Item() {

    public Item(Integer id, String name, String category) { = id; = name;
        this.category = category;

    public Integer getId() {
        return id;

    public void setId(Integer id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getCategory() {
        return category;

    public void setCategory(String category) {
        this.category = category;

Creating Item Service

import com.onlinetutorialspoint.model.Item;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ItemService {
    public static List<Item> items;
        items = new ArrayList<>(Arrays.asList(new Item(1,"Spring Boot in Action","Books"),
                new Item(2,"Java 8 in Action","Books"),
                new Item(3,"Data Structures","Books")));

    public List<Item> getAllItems(){
        return items;

    public void addItem(Item item){
    public void deleteItem(int id){
        items.removeIf(i -> i.getId().equals(id));


Creating Item Controller
package com.onlinetutorialspoint.controller;

import com.onlinetutorialspoint.model.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;

public class ItemController {
    ItemService itemService;

    public ResponseEntity<List<Item>> getAllItems(){
        List<Item> items =  itemService.getAllItems();
        return new ResponseEntity<List<Item>>(items, HttpStatus.OK);

    @PostMapping(value = "/addItem",consumes = {"application/json"},produces = {"application/json"})
    public ResponseEntity<Item> addItem(@RequestBody Item item,UriComponentsBuilder builder){
        HttpHeaders headers = new HttpHeaders();
        return new ResponseEntity<Item>(headers, HttpStatus.CREATED);

    public ResponseEntity<Void> deleteItem(@PathVariable int id){
        return new ResponseEntity<Void>(HttpStatus.ACCEPTED);

Main class:

package com.onlinetutorialspoint;

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

public class Application {

  public static void main(String[] args) {, args);

Run the application:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 :: Spring Boot ::        (v2.0.5.RELEASE)

2018-10-21 13:00:44.551  INFO 6856 --- [           main] com.onlinetutorialspoint.Application     : Starting Application on DESKTOP-RN4SMHT with PID 6856 (E:\work\SpringBoot-InMemory-Security-Example\target\classes started by Lenovo in E:\work\SpringBoot-InMemory-Security-Example)
2018-10-21 13:00:44.559  INFO 6856 --- [           main] com.onlinetutorialspoint.Application     : No active profile set, falling back to default profiles: default

Access the application:

Reading allItems with valid user credentials.

Spring Boot In Memory Basic Authentication ReadAll Success

Reading allItems with invalid user credentials.

Spring Boot In Memory Basic Authentication ReadAll Unauthorized

Deleting Item with admin user.

Spring Boot In Memory Basic Authentication Delete Success

Deleting an Item with an unknown user.

Spring Boot In Memory Basic Authentication Delete Unauthorized


Spring Boot Security Docs

Happy Learning 🙂

Download Example

About the Author:

Founder of Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment