Skip to content

Roles and authorities are being overridden in GrantedAuthority and are not accessible within the AuthenticationManager. #17002

Closed
@surajbh123

Description

@surajbh123

User Builder Class Authority Override Issue

Problem Description

The User.builder() class has an issue where data gets overridden depending on the order of method calls. Specifically, there's a conflict between the .authorities() and .roles() methods.

Issue Demonstration

Scenario 1: Authorities Added First, Then Roles

java

UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder.encode("user"))
                // first adding authorities
                .authorities("read", "item:view") 
                // authorities getting overridden by role
                .roles("USER")
                .accountExpired(false)
                .accountLocked(false)
                .credentialsExpired(false)
                .disabled(false)
                .build();

Result: authorities = ["ROLE_USER"]

Scenario 2: Roles Added First, Then Authorities

java

UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder.encode("user"))
                // first adding role
                .roles("USER")
                // role getting overridden by authorities
                .authorities("read", "item:view") 
                .accountExpired(false)
                .accountLocked(false)
                .credentialsExpired(false)
                .disabled(false)
                .build();

Result: authorities = ["read", "item:view"]

Explanation

The issue occurs because both .roles() and .authorities() methods modify the same underlying collection of authorities:

  1. When .roles("USER") is called, it converts the role to "ROLE_USER" and sets it as the sole authority, overwriting any previous authorities.
  2. When .authorities("read", "item:view") is called, it sets these values as the authorities, overwriting any previous authorities including those set by .roles().
  3. The last method called takes precedence, which explains the different results in the two scenarios.

This behavior can lead to unexpected security configurations where permissions are accidentally overridden based on the order of builder method calls.

Metadata

Metadata

Assignees

Labels

in: coreAn issue in spring-security-corestatus: invalidAn issue that we don't feel is valid

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions