Category: java
Introduction to OAuth2
Published on 24 Jul 2026
Explanation
OAuth2 is an authorization framework that allows users to log in using third-party providers such as Google, GitHub, or Facebook without sharing their passwords with the application. Spring Security provides built-in support for OAuth2 login and resource servers.
Code:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
Explanation
Role-Based Access Control restricts access to application resources based on user roles. For example, an ADMIN can manage users, while a USER can only access their own data. Spring Security uses roles to enforce authorization rules.
Code:
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated());
Explanation
Method Security secures individual service or controller methods instead of entire URL patterns. By enabling @EnableMethodSecurity, you can apply authorization rules directly on methods using annotations such as @PreAuthorize.
Code:
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
}
Explanation
The @PreAuthorize annotation checks a user's roles or permissions before executing a method. If the required role is missing, Spring Security automatically returns an Access Denied response without executing the business logic.
Code:
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/students")
public List<Student> getStudents() {
return service.findAll();
}
Explanation
In modern Spring Boot applications, OAuth2 authenticates users, JWT carries user identity and roles between requests, and Role-Based Access Control along with Method Security ensures users can access only the resources they are authorized to use.
Code:
User Login
↓
OAuth2 Authentication
↓
JWT Generated
↓
Spring Security
↓
@PreAuthorize Checks Role
↓
Access Granted