Describe the bug Bugs occur when roles and authorities are built at the same time. The content is overwritten by the latter

To Reproduce

when use code under line to build UserDetails, the value of authorities will be empty.

           UserDetails userDetails = User.withDefaultPasswordEncoder()
                    .username("admin")
                    .password("123456")
                    .roles("admin")
                    .authorities("admin:get")
                    .build();

Spring Security Bugs occur when roles and authorities are built at the same time

the reason is at line 444 under package org.springframework.security.core.userdetails and class User

Spring Security Bugs occur when roles and authorities are built at the same time

Expected behavior

Since a method of continuous execution is provided, the results should be as expected.

so it should be :

    this.authorities.addAll(authorities);

Versions spring-security-core:6.1.5

Reports that include a sample will take priority over reports that do not. At times, we may require a sample, so it is good to try and include a sample up front.

Comment From: sjohnr

@vanga-top thanks for your interest in the project and the suggestion

when use code under line to build UserDetails, the value of authorities will be empty.

I'm not sure I understand this but it seems to be an inaccurate statement, which is demonstrated by your screenshot.

Since a method of continuous execution is provided, the results should be as expected.

so it should be :

java this.authorities.addAll(authorities);

The change you are suggesting is a breaking change. The builder methods authorities(..) and roles(...) are intended to replace the authorities. You can achieve the desired result with the following:

           UserDetails userDetails = User.withDefaultPasswordEncoder()
                    .username("admin")
                    .password("123456")
                    .authorities("ROLE_admin", "admin:get")
                    .build();

Perhaps it would be worthwhile to open an enhancement for additional builder methods that only add a single authority to the list, e.g. role(String), authority(String). But in any case, that would be a separate enhancement.

I'm going to close this issue as we don't want to make a breaking change.