Spring Security - Authorization and Authentication
Spring Security is a framework that provides authentication and authorization for web applications, as well as protection against common attacks. Authentication is how we verify the identity of who is trying to access a particular resource, such as by entering a username and password. Authorization is how we check the permissions of an authenticated user, such as by assigning roles or access levels¹².
Spring Security is based on the concept of servlet filters, which are components that intercept and process requests before they reach the servlet or controller. Spring Security provides a number of filters that handle different aspects of security, such as authentication, authorization, session management, CSRF protection, etc. You can configure these filters using Java or XML configuration, or by using annotations²³.
Spring Security also integrates well with other frameworks and standards, such as Spring Web MVC, Spring Boot, OAuth2, SAML, JWT, etc. You can use these technologies to implement various authentication and authorization scenarios, such as stateless authentication, single sign-on, social login, etc.
Practical- Implementing Authentication and Authorization with Spring Boot Security.
Security.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
@EnableWebSecurity
public class Security extends WebSecurityConfiguration{
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/").hasRole("USER")
.requestMatchers("/about").hasRole("ADMIN")
.anyRequest().authenticated()
)
.httpBasic(withDefaults())
.formLogin(withDefaults());
return http.build();
}
@Bean
public InMemoryUserDetailsManager userDetailsService() {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
//PasswordEncoder encoder = new MessageDigestPasswordEncoder("SHA-1");
System.out.println(encoder.encode("password"));
UserDetails user = User.withUsername("user")
.password("{bcrypt}$2a$10$u2kV5i1Hcz2aThxm8pCJH.KayaLcgoI8Fl1lSyBJ18daKH9AtHGWy")
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password(encoder.encode("password"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user,admin);
}
}
LoginController.java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
@GetMapping("/")
public String home()
{
return ("<h1>Welcome</h1>");
}
@GetMapping("/about")
public String about()
{
return ("<h1>Welcome to about</h1>");
}
}
After this, simply run the main or primary application file in your spring boot project and you are ready to go.