spring-projects / spring-projects/spring-security

Using a custom role prefix breaks "hasRole('ANONYMOUS')"

Open
#19,673 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

status: waiting-for-triage type: bug
Dominant language
Java
Stars
9.6k
Forks
6.3k
Avg merge
2d 11h
Merged PRs (30d)
52

Description

Default behavior
In a standard spring boot application with spring security this matches when the user is anonymous because the user has been given the ROLE_ANONYMOUS and the default prefix is ROLE_.

@PreAuthorize("hasRole('ANONYMOUS')")

My context
In my project I have a custom Bean that forces a non-standard (randomized) role prefix. I do this to reduce what I see as a possible attack vector.

Simplified I have:

@Bean
fun grantedAuthorityDefaults(): GrantedAuthorityDefaults {
    return GrantedAuthorityDefaults("SOMETHING_DIFFERENT_")
}

Bug description
What I found is that in many places in the Spring Security codebase the role prefix for the ANONYMOUS role has been hardcoded to ROLE_.

I see in many places code similar to this
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS");

Since the above mentioned @PreAuthorize("hasRole('ANONYMOUS')") expression actually checks using the custom prefix for SOMETHING_DIFFERENT_ANONYMOUS, this will no longer match the actually present ROLE_ANONYMOUS.

Workaround?
I now have custom code that adds an "ANONYMOUS" role with the configured prefix (which can be anything including the default "ROLE_") to the list of authorities.

This overrules the default functionality and now it works again... in the test cases I tried. I'm NOT sure I have covered all cases with this.

http
 .anonymous { it.authorities(listOf(SimpleGrantedAuthority("${grantedAuthorityDefaults.rolePrefix}ANONYMOUS")))

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the Spring Security code paths containing AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS") and compare them with the GrantedAuthorityDefaults bean and @PreAuthorize("hasRole('ANONYMOUS')") behavior. Verify the anonymous authority consistently uses the configured role prefix, including the custom-prefix cases described in the issue, and confirm the affected test cases pass.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
authorization
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.