Guide to Spring Security
Guide to Spring Security
10.2 Pom.xml
Dependencies installed:-
list of the dependencies and their usage:
1. spring-boot-starter-security
2. spring-boot-starter-web
o Adds support for building web applications (RESTful services, etc.) in Spring Boot.
3. spring-boot-devtools
o Enhances the development experience with automatic restarts and live reload
features (used during development only).
4. spring-boot-starter-test
o Provides testing libraries like JUnit, Mockito, and Spring Test for writing tests in
Spring Boot applications.
5. spring-security-test
o Provides support for testing Spring Security configurations in unit and integration
tests.
6. lombok
7. spring-boot-starter-data-jpa
o Provides support for JPA (Java Persistence API) to simplify database access and
management with Spring Data.
8. mysql-connector-j
o MySQL JDBC driver for connecting and interacting with MySQL databases.
9. spring-boot-starter-thymeleaf
o Integrates the Thymeleaf template engine with Spring Boot for rendering dynamic
HTML views.
10.thymeleaf-extras-springsecurity6
o Provides Spring Security integration for Thymeleaf templates, enabling features like
security tags and authentication checks in views.
10.3 Config/SecurityConfig
@Bean: This annotation is used to define a bean in the Spring context. It marks a
method as producing a bean to be managed by the Spring container.
BCryptPasswordEncoder passwordEncoder(): This method creates and returns
a BCryptPasswordEncoder bean, which is used for encoding passwords using the
BCrypt hashing algorithm. The number 12 represents the strength factor (higher
values increase computation time, improving security). This encoder is typically
used to hash and verify user passwords.
1. CSRF Protection:
2. Authorization Rules:
requestMatchers("/login", "/register",
"/perform_register").permitAll(): Allows unauthenticated access
to login, register, and registration submission pages.
4. Logout Configuration:
6. Session Management:
sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED):
Configures the session creation policy, where a session is created
only if required. This is often used to avoid unnecessary session
creation, especially in stateless scenarios like REST APIs.
7. .build(): Finally, the SecurityFilterChain is built and returned, applying all the
above security settings to the application.
http.getSharedObject(AuthenticationManagerBuilder.class): This
retrieves the AuthenticationManagerBuilder object from the HttpSecurity
object to configure it with the custom authentication provider.
authenticationProvider(authenticationProvider): Registers the
DaoAuthenticationProvider as the authentication provider for Spring
Security.
build(): Builds and returns the AuthenticationManager instance that is
configured with the custom authentication provider and password encoder.
10.4 P4-SecurityApplication.java
@Entity: Marks the class as a JPA entity, meaning it is mapped to a database table.
private int id: Represents the primary key of the entity. The field is mapped to a
column in the database table.
@Id: Marks the id field as the primary key for the entity.
private String username: Represents a column for the user's username.
private String password: Represents a column for the user's password.
Getters,Setters,NoArgCountructors,AllArgCunstructrs,ToStringMthod ara
also included in the code.
10.6 Repo/UsersRepository
@Service: Marks the class as a Spring service, making it a candidate for dependency
injection and indicating it contains business logic.
@Transactional: Ensures that all methods in the class are executed within a
transaction context, providing atomicity.
@Autowired: Injects the UsersRepository bean into the service to interact with the
database so that it can use the methods implemented by the Repo file.
BCryptPasswordEncoder: Used for encoding the user's password before storing it
in the database.
register(Users user):
Checks if a user with the same username already exists using
findBytheUsername.
If the user exists, it returns "User Already Available".
If not, it encrypts the password and saves the new user to the repository,
returning "User Registered Successfully".
10.8 Servises/CustomUserDetailsService
loadUserByUsername(String username):
userOptional.get(): If the user is found, it retrieves the Users object from the
Optional.
o password: Set from the Users entity's password (which should be already
encoded).
The User object constructed with these details is then returned, which will be
used by Spring Security for authentication and authorization.
The CustomUserDetailsService class loads user details (username,
password, and roles) from the database using the UsersRepository. It
throws an exception if the user is not found and constructs a
UserDetails object for authentication with Spring Security.
10.9 Controller/UsersController
@Controller: Marks the class as a Spring MVC controller that handles web
requests and returns views (typically HTML).
@GetMapping("/register"): Maps HTTP GET requests to the /register URL and
invokes the register() method.
register(): Returns the name of the view ("register") to be rendered, typically a
registration form page.
10.11 Controller/LoginController
@Controller: Marks the class as a Spring MVC controller that handles
web requests and returns view names.
@GetMapping("/login"): Maps HTTP GET requests to the /login URL,
returning the "login" view (usually a login form).
@GetMapping("/success"): Maps HTTP GET requests to the /success
URL, returning the "success" view (usually a success page after login).
11. Conclusion
Spring Security is essential for building secure Java applications. Its flexibility,
wide range of features, and seamless integration with Spring Boot make it the
go-to solution for securing enterprise applications. Understanding and
implementing Spring Security ensures robust protection against common
threats while allowing for scalable and maintainable security configurations.