← Back to Questions
Spring Boot

What is authorization in Spring Security?

Learn What is authorization in Spring Security? with simple explanations, real-time examples, interview tips and practical use cases.

What is Authorization in Spring Security?

Authorization in Spring Security is the process of determining whether an authenticated user has permission to access specific resources, APIs, pages, or operations in an application.

After a user is authenticated, Spring Security checks what actions the user is allowed to perform.

In simple words, authorization answers the question:

β€œWhat are you allowed to access?”

Why Authorization is Important

Applications contain different types of users such as:

  • Admin
  • Manager
  • Student
  • Employee
  • Customer

Every user should not access all features.

Examples:

  • Admin can delete users
  • Student can view courses only
  • Customer can view personal orders only
  • Manager can approve employee requests

Without authorization:

  • Unauthorized users may access sensitive data
  • Security vulnerabilities increase
  • Business rules become weak
  • Data privacy may be compromised

Authorization protects applications by restricting access based on permissions and roles.


Real-Life Authorization Example

Consider a company office:

  • Employees can enter general areas
  • Managers can access meeting rooms
  • Admins can access server rooms

Here:

  • Identity verification β†’ Authentication
  • Area access permission β†’ Authorization

Authentication vs Authorization

Feature Authentication Authorization
Main Purpose Verify identity Check permissions
Main Question Who are you? What can you access?
Occurs First Yes No
Example Login Role-based access

How Authorization Works in Spring Security

Authorization flow:

  1. User logs in successfully
  2. Spring Security authenticates the user
  3. User roles and authorities are loaded
  4. User requests protected resource
  5. Spring Security checks permissions
  6. Access is granted or denied

Main Components Involved in Authorization

Component Purpose
GrantedAuthority Represents user permission
Role Group of permissions
SecurityContext Stores authenticated user details
SecurityFilterChain Defines authorization rules

What are Roles in Spring Security?

Roles define categories of users.

Examples:

  • ROLE_ADMIN
  • ROLE_STUDENT
  • ROLE_MANAGER
  • ROLE_USER

Roles are usually stored in:

  • Database
  • JWT token
  • Memory

Spring Security Dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Simple Authorization Example

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(
            HttpSecurity http) throws Exception {

        http
            .authorizeHttpRequests(auth -> auth

                .requestMatchers("/admin/**")
                .hasRole("ADMIN")

                .requestMatchers("/student/**")
                .hasRole("STUDENT")

                .requestMatchers("/public/**")
                .permitAll()

                .anyRequest()
                .authenticated()
            )
            .formLogin(Customizer.withDefaults());

        return http.build();
    }
}

Explanation of Authorization Rules

Rule Meaning
hasRole("ADMIN") Only ADMIN users allowed
hasRole("STUDENT") Only STUDENT users allowed
permitAll() Accessible by everyone
authenticated() Requires login

What Happens When Access is Denied?

If user does not have required permission:

  • Spring Security blocks access
  • HTTP 403 Forbidden is returned

HTTP 403 Example

403 FORBIDDEN

Method-Level Authorization

Spring Security supports authorization at method level using annotations.


@PreAuthorize Example

@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin/dashboard")
public String adminDashboard() {

    return "Admin Dashboard";
}

Enable Method Security

@Configuration
@EnableMethodSecurity
public class SecurityConfig {
}

Other Authorization Annotations

Annotation Purpose
@PreAuthorize Checks access before method execution
@PostAuthorize Checks access after method execution
@Secured Role-based access restriction
@RolesAllowed Standard role authorization

@Secured Example

@Secured("ROLE_ADMIN")
@GetMapping("/delete")
public String deleteUser() {

    return "User Deleted";
}

Authorization Using Authorities

Authorities are fine-grained permissions.

Example:

  • READ_COURSE
  • WRITE_COURSE
  • DELETE_USER

Authority-Based Example

@PreAuthorize("hasAuthority('DELETE_USER')")
public String deleteUser() {

    return "Deleted";
}

Role vs Authority

Feature Role Authority
Purpose User category Specific permission
Example ROLE_ADMIN DELETE_USER
Granularity Broad Detailed

Authorization in JWT Authentication

In JWT authentication:

  • User roles are stored inside token
  • Spring Security extracts roles from token
  • Authorization rules are applied

JWT Payload Example

{
   "sub": "naresh",
   "roles": ["ROLE_ADMIN"]
}

Real-Time Example in Banking Application

Suppose a banking system contains:

  • Customer dashboard
  • Admin dashboard
  • Money transfer APIs

Authorization rules:

  • Customers can view their accounts
  • Admins can manage all users
  • Managers can approve loans

Example Configuration

http
.authorizeHttpRequests(auth -> auth

    .requestMatchers("/admin/**")
    .hasRole("ADMIN")

    .requestMatchers("/customer/**")
    .hasRole("CUSTOMER")

    .requestMatchers("/manager/**")
    .hasRole("MANAGER")
)

Advantages of Authorization in Spring Security

  • Protects sensitive resources
  • Supports role-based access control
  • Supports authority-based permissions
  • Works with JWT and OAuth2
  • Improves application security
  • Supports enterprise applications

Disadvantages of Authorization

  • Complex role management in large systems
  • Improper configuration may expose resources
  • Fine-grained permissions may increase complexity

Best Practices for Authorization

  • Follow least privilege principle
  • Use role-based access control
  • Separate roles and authorities properly
  • Secure sensitive endpoints
  • Use method-level security when needed
  • Validate JWT roles carefully
  • Avoid exposing admin APIs publicly

Common Authorization Exceptions

Exception Description
AccessDeniedException User lacks required permission
AuthenticationCredentialsNotFoundException User not authenticated

Difference Between permitAll() and authenticated()

Method Meaning
permitAll() Accessible without login
authenticated() Requires authentication

Common Interview Questions on Authorization

What is authorization in Spring Security?

Authorization determines whether an authenticated user can access specific resources or operations.

What is the difference between authentication and authorization?

Authentication verifies identity, while authorization checks permissions.

What is the purpose of @PreAuthorize?

It performs method-level access control before method execution.

What is the difference between roles and authorities?

Roles represent user categories, while authorities represent detailed permissions.

What HTTP status is returned when access is denied?

Spring Security usually returns:

403 FORBIDDEN

Conclusion

Authorization is one of the most important security mechanisms in Spring Security.

It controls what authenticated users can access and prevents unauthorized operations.

Spring Security provides powerful authorization features such as:

  • Role-based access control
  • Authority-based permissions
  • Method-level security
  • JWT authorization

Proper authorization implementation is critical for protecting enterprise applications, banking systems, REST APIs, and microservices.

Understanding authorization is essential for Spring Boot developers because access control is a mandatory requirement in secure backend systems.

Why this Spring Boot question is important?

This interview question helps candidates understand real-time backend development concepts, practical problem solving, coding fundamentals, system design basics and production-ready application behavior.

Practice this question carefully for Java backend roles, Spring Boot developer interviews, microservices interviews, company interviews and full-stack developer preparation.

About the Author

Naresh Kumar is a Senior Java Backend Engineer with experience building enterprise applications using Java, Spring Boot, Microservices, Docker, Kubernetes and Cloud technologies.