Skip to content

Spring Security Basic Introduction#

Why Spring Security?#

  • Spring Security built by a team at Spring who are good at security by considering all the security scenarios. Using Spring Security, we can secure web apps with minimun configurations. So there is no need to re-invent the wheel here.
  • Spring Security handles the common security vulnerabilities like CSRF, CORs etc. For any security vulnerabilities identifies, the framework will be patched immediately as it is being used by many organizations.
  • Using Spring Security we can secure our pages/API paths, enforce roles, method level security etc. with minimum configuration easily.
  • Spring Security supports various standards of security to implement authentication, like using username/password authentication, JWT tokens, OAuth2, OpenID etc.

Spring Security Basic#

  • In this section we will use apply Spring security on SpringBoot application.
  • You can add dependencies as below to enable default spring security for your SpringBoot application.
pom.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.6.4</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>2.6.4</version>
</dependency>
  • Then, we will create a simple REST controller as below.
WelcomeController.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package com.springboot.security.spring.security.basic.controller;  

import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RestController;  

@RestController  
public class WelcomeController {  

    @GetMapping("/welcome")  
    public String sayWelcome() {  
        return "Welcome from spring application with security";  
    }  

}
  • Then let's build and start up your SpringBoot application. By default, without any configuration, when you start a your spring boot service, spring security will be applied to your all apis with basic authentication (username/password ) and the default user name is user, the default password is generated and showed in the log when you start your application ex: 696d439c-14c5-44b1-ae60-1814ab7973c9(Note: every time you start up your SpringBoot application, it will generate another password). See the example log below.
1
2
3
4
5
6
7
8
2022-03-05 15:46:14.587  INFO 36968 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-03-05 15:46:14.588  INFO 36968 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1287 ms
2022-03-05 15:46:15.008  INFO 36968 --- [           main] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: 696d439c-14c5-44b1-ae60-1814ab7973c9

2022-03-05 15:46:15.140  INFO 36968 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will not secure any request
2022-03-05 15:46:15.235  INFO 36968 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
  • Let's open postman and call the api with the credential as above you should see the result.

 #zoom

  • Using generated password in log is hard for us to use our application. So we will need adding some configuration in application.yml to override the default username/password for basic authentication.
application.yml
1
2
3
4
5
spring:
    security:
        user:
            name: user
            password: 12345
  • Then start your SpringBoot service again and you will see there isn't any generated password printed in the log.

1
2
3
4
2022-03-05 15:57:48.366  INFO 37759 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-03-05 15:57:48.366  INFO 37759 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1095 ms
2022-03-05 15:57:48.954  INFO 37759 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will not secure any request
2022-03-05 15:57:49.024  INFO 37759 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
- Now, you can use your custom username/password to execute the api.

 #zoom

Understand On How Multiple Requests Work Without Credentials#

  • Some of us may will try to execute the api multi time then can recognize that for the first time you execute the api with credentials after the SpringBoot application has started it took a longer time than the second time or the third time. So why does this happen?
  • Okay, Let's restart your SpringBoot application again, then call the api with credentials.

 #zoom

  • Now, try to choose No Auth from postman, then call api again. Then you will see it's still success without adding username/password for basic authentication. So how does it work?

 #zoom

  • It is due to the power of a cookie present inside your header request, if you use postman to call your api, you will see, with the first time you put a username and password then you will see the response is successful with 1 cookie, in this cookie you will see the name is JSESSIONID and a value for example: 4C107DAA04E80446EA6AAFBA2914E5A6 . So this cookie contains a Session that is generated from your SpringBoot service with the help of spring security at the first time you login (please review Spring Security Internal Flow And Architecture), then for next times you just request to spring boot application with this cookie then you will be authenticated without login.

Set Session Timeout#

  • For the demo above, after the first time you are authenticated, so can use the session in cookie for onwards calls. By default, this session is infinity timeout, it means, you can use this session forever to access the api without username/password authentication except you restart your springboot application.
  • So doing this way is not a best practice for security, because attacker can access your devices when you go away.
  • To set timeout for session you can add the configuration below into your application.yml.
application.yml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
spring:  
  security:  
    user:  
      name: user  
      password: 12345  

server:  
  servlet:  
    session:  
      timeout: 1m
  • In which, the session will be destroyed in 1 minutes if you do nothing (make request to your springboot application) after your first request is authenticated successfully. See results in the images below.

 #zoom  #zoom

See Also#

References#