If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:
>> LEARN SPRING SECURITYMocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Overview
In this quick article, weβll explain the subtle but significant difference between a Role and a GrantedAuthority in Spring Security. For more detailed information on roles and authorities, see the article here.
Further reading:
Spring Security Basic Authentication
2. GrantedAuthority
In Spring Security, we can think of each GrantedAuthority as an individual privilege. Examples could include READ_AUTHORITY, WRITE_PRIVILEGE, or even CAN_EXECUTE_AS_ROOT. The important thing to understand is that the name is arbitrary.
When using a GrantedAuthority directly, such as through the use of an expression like hasAuthority(βREAD_AUTHORITYβ), we are restricting access in a fine-grained manner.
As you can probably gather, we can refer to the concept of authority by using privilege as well.
3. Role as Authority
Similarly, in Spring Security, we can think of each Role as a coarse-grained GrantedAuthority that is represented as a String and prefixed with βROLEβ. When using a Role directly, such as through an expression like hasRole(βADMINβ), we are restricting access in a coarse-grained manner.
It is worth noting that the default βROLEβ prefix is configurable, but explaining how to do that is beyond the scope of this article.
The core difference between these two is the semantics we attach to how we use the feature. For the framework, the difference is minimal β and it basically deals with these in exactly the same way.
4. Role as Container
Now that weβve seen how the framework uses the role concept, letβs also quickly discuss an alternative β and that is using roles as containers of authorities/privileges.
This is a higher level approach to roles β making them a more business-facing concept rather than an implementation-centric one.
The Spring Security framework doesnβt give any guidance in terms of how we should use the concept, so the choice is entirely implementation specific.
5. Spring Security Configuration
We can demonstrate a fine-grained authorization requirement by restricting access to /protectedbyauthority to users with READ_AUTHORITY.
We can demonstrate a coarse-grained authorization requirement by restricting access to /protectedbyrole to users with ROLE_USER.
Letβs configure such a scenario in our security configuration:
@Override
protected void configure(HttpSecurity http) throws Exception {
// ...
.requestMatchers("/protectedbyrole").hasRole("USER")
.requestMatchers("/protectedbyauthority").hasAuthority("READ_PRIVILEGE")
// ...
}
6. Simple Data Init
Now that we understand the core concepts better, letβs talk about creating some setup data when the application starts up.
This is, of course, a very simple way of doing that, to hit the ground running with some preliminary test users during development β not the way you should handle data in production.
Weβre going to be listening for the context refresh event:
@Override
@Transactional
public void onApplicationEvent(ContextRefreshedEvent event) {
MyPrivilege readPrivilege
= createPrivilegeIfNotFound("READ_PRIVILEGE");
MyPrivilege writePrivilege
= createPrivilegeIfNotFound("WRITE_PRIVILEGE");
}
The actual implementation here doesnβt really matter β and generally, depends on the persistence solution youβre using. The main point is β weβre persisting the authorities weβre using in the code.
7. UserDetailsService
Our implementation of UserDetailsService is where the authority mapping takes place. Once the user has authenticated, our getAuthorities() method populates and returns a UserDetails object:
private Collection<? extends GrantedAuthority> getAuthorities(
Collection<Role> roles) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (Role role: roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
authorities.addAll(role.getPrivileges()
.stream()
.map(p -> new SimpleGrantedAuthority(p.getName()))
.collect(Collectors.toList()));
}
return authorities;
}
8. Running and Testing the Example
We can execute the example RolesAuthoritiesApplication Java application, found in the GitHub project.
To see the role-based authorization in action, we need to:
- Access http://localhost:8082/protectedbyrole
- Authenticate as [email protected] (password is βuserβ)
- Note successful authorization
- Access http://localhost:8082/protectedbyauthority
- Note unsuccessful authorization
To see authority-based authorization in action, we need to log out of the application and then:
- Access http://localhost:8082/protectedbyauthority
- Authenticate as [email protected] / admin
- Note successful authorization
- Access http://localhsot:8082/protectedbyrole
- Note unsuccessful authorization
9. Conclusion
In this quick tutorial, we looked at the subtle but significant difference between a Role and a GrantedAuthority in Spring Security.
