Guide to Spring Security
Guide to Spring Security
Guide to Spring Security
10.2 Pom.xml
Dependencies installed:-
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
o A utility library to reduce boilerplate code in Java (e.g., generating getters/setters, constructors, etc.).
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
• @Configuration: Marks the class as a configuration class, indicating that it contains Spring bean definitions
(like a Java-based alternative to XML configuration).
• @EnableWebSecurity: Enables Spring Security's web security features, allowing you to configure
authentication, authorization, and security settings for a web application.
• @Autowired: This annotation is used for automatic dependency injection in Spring. It allows Spring to
automatically wire the customUserDetailsService bean into the class.
• customUserDetailsService: A reference to a custom service (likely implementing UserDetailsService) used for
loading user-specific data during authentication. It is typically used to fetch user information from a database or
other source during the authentication process.
• @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.
SecurityFilterChain securityFilterChain(HttpSecurity http): This method defines the security filter chain for a
Spring Security configuration. The HttpSecurity object is used to customize the security settings (e.g., setting up
authentication, authorization, and configuring which requests are permitted or denied). The SecurityFilterChain bean
ensures that the defined security filters are applied to the application.
1. CSRF Protection:
2. Authorization Rules:
4. Logout Configuration:
6. Session Management:
7. .build(): Finally, the SecurityFilterChain is built and returned, applying all the above security settings to the
application.
• authenticationManager(HttpSecurity http): This method customizes the AuthenticationManager,
which is used by Spring Security to authenticate users. It configures a DaoAuthenticationProvider for
authenticating users with a database.
• DaoAuthenticationProvider authenticationProvider:
10.4 P4-SecurityApplication.java
10.5 Entity/Users
• @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
• @Repository: Marks the interface as a Spring Data repository for database interaction.
• UsersRepository extends JpaRepository<Users, Integer>: Provides built-in CRUD operations for the Users
entity with Integer as the primary key.
• findByUsername(String username): A derived query method automatically implemented by Spring Data JPA
to find a user by their username.
• @Query(...): A custom native SQL query to retrieve a user by their username.
10.7 Service/UserService
• @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.
• User.builder(): This is a Spring Security User object (which implements UserDetails). The builder pattern
is used to construct a User instance with the following:
o password: Set from the Users entity's password (which should be already encoded).
o roles("USER"): Here, a fixed role ("USER") is assigned to the user. In a real-world application,
roles would typically be fetched from the database, but in this case, a default role is used.
• 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
This controller processes user registration by receiving user data, delegating registration to the
service, and returning a status message.
10.10 Controller/SignUpController
• @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.