Roles vs authorities
Stop guessing about the ROLE_ prefix and model permissions in a way that scales.
Open this lesson in the learning hubKey points
- A
GrantedAuthorityis just a string. Spring Security attaches no meaning to it. - A role is just an authority with the
ROLE_prefix.hasRole("ADMIN")looks forROLE_ADMIN. hasAuthoritycompares the string exactly, so it needs the fullhasAuthority("ROLE_ADMIN").- A huge share of mystery 403s is a missing or doubled
ROLE_prefix. Pick one convention and store it consistently. - Coarse roles say who you are (ADMIN). Fine authorities say what you may do (
post:delete). Check permissions in business code.
Example
// What you store on the user
new SimpleGrantedAuthority("ROLE_ADMIN"); // a role
new SimpleGrantedAuthority("post:delete"); // a permission
http.authorizeHttpRequests(a -> a
.requestMatchers("/admin/**").hasRole("ADMIN") // matches ROLE_ADMIN
.requestMatchers("/reports/**").hasAnyRole("ADMIN", "AUDITOR")
.requestMatchers(HttpMethod.DELETE, "/api/posts/**")
.hasAuthority("post:delete") // exact string
.anyRequest().authenticated());
hasRole adds ROLE_ for you; hasAuthority does not. That one line explains most 403s.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Security course, and every lesson in it is listed on the Spring Security contents page.