Session 05: Spring Security (cont)
Objectives
• JSON Web Token (review)
• Spring Security (cont)
• Spring Security Annotations
R2S Academy - Internal Use 2
JSON Web Token (1)
What is JWT?
• A JSON Web Token (JWT) is an way for securely transmitting information
between parties as a JSON object. This information can be verified and trusted
because it is digitally signed.
• JWT defines the structure of information we are sending from one party to the
another. The token is mainly composed of header, payload, signature
<header>.<payload>.<signature>
• Structure of a JWT:
- Header: Contains the token type (JWT) and signing algorithm (e.g., HS256)
- Payload: Contains claims, which are pieces of information about the user (e.g., username,
roles).
- Signature: Generated by hashing the header and payload with a secret key server-side. This
ensures the token's integrity and prevents modification.
R2S Academy - Internal Use 3
JSON Web Token (2)
What is JWT?
• JWTs are commonly used for Authorization: Once the user is logged in, each subsequent
request will include the JWT, allowing the user to access routes, services, and resources
that are permitted with that token.
R2S Academy - Internal Use 4
JSON Web Token (2)
Example
• Header: Contains the token type (JWT)
and signing algorithm (e.g., HS256)
• Payload: Contains claims, which are
pieces of information about the user
(e.g., username, roles).
• Signature: Generated by hashing the
header and payload with a secret key
server-side. This ensures the token's
integrity and prevents modification.
4fH6y0cy28gSXLcbTyAeR12JfxEKK2R/aU8/7IYRQdE=
R2S Academy - Internal Use 5
Spring Security (1)
What is Spring Security
• Spring security provides authentication and authorization to our application
using simple servlet filters
• Example: Unauthorized
R2S Academy - Internal Use 6
Spring Security (2)
What is Spring Security
• Spring security provides authentication and authorization to our application
using simple servlet filters
• Example: Authorized
R2S Academy - Internal Use 7
Spring Security (3)
Authorization Architecture
Authentication Architecture
R2S Academy - Internal Use 8
Spring Security (4)
Authorization Architecture
POST /api/order
Secured POST /api/order
Setting Authorization Securing POST /error
OrderController
R2S Academy - Internal Use 9
Spring Security Annotations (1)
Overview
• Annotations like @Secured, @PreAuthorize, @PostAuthorize, @PreFilter, and
@PostFilterare used to secure methods by restricting access based on roles and conditions.
• Example: Role-based Authorization
Setting Authorization Using annotation
R2S Academy - Internal Use 10
Spring Security Annotations (2)
Overview
• @PreAuthorize:
- It’s an annotation used for method-level security. You can use it to secure individual
methods based on the current authentication and optionally, the method’s parameters.
- For example, @PreAuthorize("hasRole('ADMIN')") would only allow users with the ‘ADMIN’
role to access the annotated method.
Setting Authorization: URL Using annotation: method-level
R2S Academy - Internal Use 11
Spring Security Annotations (3)
Overview
• filterChain:
- It’s a method used for web-level security.
- It allows you to configure security features like URL-based security, and more.
- For instance, .requestMatchers("/api/order/**").hasRole("ADMIN") ensures that only users
with the ‘ADMIN’ role can access URLs that match /api/order/**.
Using annotation: method-level
Setting Authorization: URL
R2S Academy - Internal Use 12
Spring Security Annotations (4)
@Secured
• Use this for simple method-level authorization based on roles. It directly lists
the required roles for access.
• Sample
@Controller
public class ProductController {
@Secured("ROLE_ADMIN")
public String addProduct(@RequestBody Product product) {
// Add product logic
return "Product added successfully!";
}
}
R2S Academy - Internal Use 13
Spring Security Annotations (5)
@PreAuthorize
• You can use it to restrict access to methods based on user roles, arguments, or other
conditions.
• Sample: We want to ensure that only the user themselves can modify their profile
@Controller
public class UserController {
@PreAuthorize("authentication.name == #username")
public void updateUserProfile(String username, UserProfile updatedProfile) {
// Implementation to update the user's profile
}
}
Explanation:
- The authentication object is a built-in object provided by Spring Security.
- It represents the current user’s authentication state.
- It contains information about the user, such as their username, roles, and authorities.
R2S Academy - Internal Use 14
Spring Security Annotations (6)
@PostAuthorize
• The @PostAuthorize annotation is used to secure the return value of a method. You can
use it to ensure that only authorized data is returned to the user.
• Sample: We want to ensure that only the book owner can access it.
@Service
public class BookService {
@PostAuthorize("returnObject.owner == authentication.name")
public Book getBook() {
// Implementation to retrieve the book
}
}
Explanation:
- The built-in keyword returnObject refers to the object returned by the method (here, “Book").
R2S Academy - Internal Use 15
Spring Security Annotations (7)
@PreFilter
• It is an annotation used to perform checks on method arguments before the actual
method execution.
• Sample
@Service
public class TaskService {
@PreAuthorize(“hasRole('MEMBER')") // Ensure user is logged in
@PreFilter(filterTarget = "tasks", targetType = "java.util.List")
public List<Task> getAuthorizedTasks(List<Task> tasks) {
// Method implementation
}
}
Explanation:
- ilterTarget: Speci ies the method argument name containing the collection to ilter (here, "tasks").
- targetType: De ines the expected type of the collection (here, a List).
R2S Academy - Internal Use 16
f
f
f
f
Spring Security Annotations (8)
@PostFilter
• It allows you to filter the return value of a method after it's been executed.
• Sample
@Service
public class CourseService {
@PostFilter("filterObject.active == true")
public List<Course> getAllCourses() {
return courseRepository.findAll();
}
}
Explanation:
- The ilterObject refers to each course object in the list
- ilterObject.active == true is the condition to keep courses where the active property is true.
R2S Academy - Internal Use 17
f
f
Spring Security Annotations (9)
In summary
• @PreAuthorize is used for method-level authorization checks before method
invocation based on user roles, permissions, or other conditions.
• @PostAuthorize is used for method-level authorization checks after method
invocation, specifically on the return value of the method.
• @PreFilter is used for filtering input collections before invoking a method
based on user-specific criteria.
• @PostFilter is used for filtering the return value of a method that returns a
collection based on user-specific criteria after the method execution.
R2S Academy - Internal Use 18
Keeping up those inspiration and the enthusiasm in the learning path.
Let confidence to bring it into your career path for getting gain the success as
your expectation.
Thank you
Contact
- Name: R2S Academy
- Email: daotao@r2s.edu.vn
Questions and Answers
- Hotline/Zalo: 0919 365 363
- Website: https://r2s.edu.vn
- Fanpage: https://www.facebook.com/r2s.tuyendung
R2S Academy - Internal Use 19