Spring Security - Intro
Spring Security Introduction
Spring Security is a very popular authentication and authorization framework. If you are building Spring based web application, Spring Security should be your go to framework for securing your application.
Note that this post and the following sprint security blog posts are used for Spring Boot application.
Security Basic Concepts
- Authentication - validate the user’s credentials
- Authorization - verify the authenticated user has permission to access certain feature of the application
- Principal - The user that is currently logged in.
- Role - Coarse grained representation of a set of Authorities. A user can have multiple roles. Roles usually starts with
ROLE_
prefix - Granted Authority - individual privilege.
Dependency
Spring Boot provides a spring-boot-starter-security starter that aggregates Spring Security-related dependencies together.
1 | <dependency> |
For spring security test support
1 | <dependency> |
Spring Security In Action
After adding spring security dependency, Spring will enable Form Authentication automatically. The default username is user and the password will be print to the console. The password will be different for every application startup.
1 | Using generated security password: 74fbc0b8-c18e-49a0-9144-95cd019d8010 |
Now you can login using user and generated random password 74fbc0b8-c18e-49a0-9144-95cd019d8010
Go to http://localhost:8080/logout
page to invalidate the session and logout of the application.
You can set a custom user name and password in application.properties file. Spring Security will use in memory authentication with the provided username and password
1 | spring.security.user.name=user |
Security Configuration
We configure Spring security by creating a configuration class that extends WebSecurityConfigurerAdapter.
We also need to add @EnableWebSecurity annotation to the configuration class. @EnableWebSecurity enable Spring Security’s web security support and provide the Spring MVC integration.
Here is what a Spring Security configuration looks like:
1 |
|
In this example, we override configure(HttpSecurity http)
method. The configuration will secure all requests and use Basic authentication instead of form base authentication.
With the above configuration we switch from form base authentication to basic authentication: