Video in progress
In Spring Security, why don't hasRole("ADMIN") and hasAuthority("ADMIN") behave the same?
hasRole adds the ROLE_ prefix itself and looks for ROLE_ADMIN. hasAuthority compares the string as it is. Depending on the name the authority was given under, one passes and the other gets 403.
📖 Answer
In Spring Security everything is a GrantedAuthority, a plain string. A "role" is just an authority that starts with ROLE_.
// when the user is created
User.withUsername("ali")
.password(encoded)
.roles("ADMIN") // -> authority "ROLE_ADMIN"
.build();
User.withUsername("vali")
.password(encoded)
.authorities("ADMIN") // -> authority "ADMIN" (no prefix)
.build();
| Check | ali | vali |
|---|---|---|
hasRole("ADMIN") |
✓ | 403 |
hasAuthority("ROLE_ADMIN") |
✓ | 403 |
hasAuthority("ADMIN") |
403 | ✓ |
A common case on prod: the roles table in the database stores ADMIN, UserDetailsService does new SimpleGrantedAuthority(role.getName()), and the controller has @PreAuthorize("hasRole('ADMIN')"). The result: even the admin gets 403.
If you write .hasRole("ROLE_ADMIN") inside authorizeHttpRequests, Spring Security 6 throws IllegalArgumentException at startup; SpEL in @PreAuthorize doesn't add the prefix twice. Still, don't write the prefix yourself.
The usual convention: authorities with ROLE_ for roles, and without a prefix for fine-grained permissions (order:read, order:refund). When you work with JWT, values from the scope claim come with the SCOPE_ prefix, which follows the same logic.
Sign up to mark studied questions and save your progress.