Master Role-Based Access Control with Spring Security: Practical Guide

This article explains how to implement role‑based access control in Spring Security by embedding roles into UserDetails, configuring HttpSecurity with hasRole/hasAnyRole/hasAuthority, handling anonymous users, and using permitAll, providing code examples and detailed explanations for each approach.

Programmer DD
Programmer DD
Programmer DD
Master Role-Based Access Control with Spring Security: Practical Guide

1. Introduction

Welcome to the Spring Security practical series. Access to restricted resources is not open to every authenticated user; for example, a user with the role A (accountant) can access finance‑related resources, while a user with role B (HR) can only access HR‑related resources. This article shows how Spring Security solves role‑based access control.

2. Write Roles into UserDetails

We use UserDetailsService to load UserDetails, and during loading we also write the user's GrantedAuthority collection into it. Persist the roles and inject them at this point, then let Spring Security handle the access policies.

3. Configure Role Access Control in HttpSecurity

3.1 Access Control by Checking User Role

httpSecurity.authorizeRequests().antMatchers("/foo/test").hasRole("ADMIN")

The method hasRole requires the role name without the ROLE_ prefix. Internally it calls hasAnyRole, which in turn calls hasAnyAuthorityName with the default prefix ROLE_.

public final boolean hasRole(String role) {
    return hasAnyRole(role);
}
hasAnyRole

checks whether the user possesses any of the supplied roles:

public final boolean hasAnyRole(String... roles) {
    return hasAnyAuthorityName(defaultRolePrefix, roles);
}

For an endpoint that should be accessible by multiple roles, e.g. /foo/test, you can write:

httpSecurity.authorizeRequests().antMatchers("/foo/test").hasAnyRole("APP","ADMIN")

The underlying implementation builds a role set with the default prefix ROLE_ and checks membership.

3.2 Access Control by Checking GrantedAuthority

You can also use hasAuthority or hasAnyAuthority. The implementation is the same as hasAnyRole, but the prefix is null, so you must provide the full authority string (e.g., ROLE_ADMIN).

httpSecurity.authorizeRequests().antMatchers("/foo/test").hasAuthority("ROLE_ADMIN") httpSecurity.authorizeRequests().antMatchers("/foo/test").hasAnyAuthority("ROLE_APP","ROLE_ADMIN")

4. Anonymous Access

Anonymous users are granted the role ROLE_ANONYMOUS. You can configure anonymous access using the same methods as above:

httpSecurity.authorizeRequests().antMatchers("/foo/test").hasAuthority("ROLE_ANONYMOUS")

Or simply:

httpSecurity.authorizeRequests().antMatchers("/foo/test").anonymous()

5. Permit All Requests

To allow all requests (both authenticated and anonymous) for a specific path:

httpSecurity.authorizeRequests().antMatchers("/foo/test").permitAll()

6. Discussion on permitAll vs anonymous

The main difference is the authentication state. When Authentication is null, permitAll simply allows the request. The anonymous() method requires an AnonymousAuthenticationToken. In practice, permitAll opens the endpoint to everyone, while anonymous focuses on the user’s anonymous status.

7. Summary

Configuring role‑based access control via Spring Security is a common and beginner‑friendly solution. The next article will cover method‑level access control.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaAuthorizationRole-Based Access ControlBackend Securityspring-security
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.