'Spring Security - Authenticate user with username

I want to authenticate user with username only. To achieve this, I am still using UsernamePasswordAuthenticationTokenbut by also passing added authorities.
Here is the code:

List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
Authentication authentication = authenticationManager.authenticate(
    new UsernamePasswordAuthenticationToken(username,null,authorities)
);

This unfortunately throws bad credentials exception. What am I missing here?
When replacing the code above with correct password for the username, it works perfectily.

Authentication authentication = authenticationManager.authenticate(
    new UsernamePasswordAuthenticationToken(username,password,authorities)
);


Solution 1:[1]

You do not need to use the AuthenticationManager if you already know they are authenticated. Instead you can just set the Authentication directly as shown below:

List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
Authentication authentication = new UsernamePasswordAuthenticationToken(username, null, authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);

Solution 2:[2]

Thanks, @ismail, I tried this and it worked.

refreshTokenService.validateRefreshToken(refreshTokenRequest.getRefreshToken());
User user = userRepository.findByUsername(refreshTokenRequest.getUsername());
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
user.getRoles().forEach(role -> grantedAuthorities.add(new SimpleGrantedAuthority(role.getRoleName())));
Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), null, grantedAuthorities);
return AuthenticationResponse.builder()
         .authenticationToken(jwtUtil.generateToken(authentication))
         .refreshToken(refreshTokenRequest.getRefreshToken())
         .username(user.getUsername())
         .build();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 İsmail Y.
Solution 2 Vishal Munagekar