Hackforge Academy

Category: java

Spel in spring security method and authorization expression

Published on 30 Sep 2026

Explanation

Spring Security uses expression-based authorization to evaluate whether a user can access a protected resource.

Code:

@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) {
    // Delete user
}

Explanation

hasRole() can restrict a method to users with a specific role.

Code:

@PreAuthorize("hasRole('ADMIN')")
public void createUser(User user) {
    // Only ADMIN can access
}

Explanation

hasAuthority() can check for a specific granted authority or permission.

Code:

@PreAuthorize("hasAuthority('USER_READ')")
public List<User> getUsers() {
    return userService.findAll();
}

Explanation

Security expressions can access the currently authenticated principal and use it in authorization decisions.

Code:

@PreAuthorize("#username == authentication.name")
public User getProfile(String username) {
    return userService.findByUsername(username);
}

Explanation

Multiple security conditions can be combined using logical operators in @PreAuthorize expressions.

Code:

@PreAuthorize("hasRole('ADMIN') or hasAuthority('USER_DELETE')")
public void deleteUser(Long id) {
    userService.delete(id);
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community