How to use a custom UsernamePasswordAuthenticationFilter with spring-security 6.3.1?

I am rebuilding an old Spring Boot application which was using old version of spring-boot and spring-security with java 8. I am currently using 3.3.2 for spring-boot and 6.3.1 for spring-security.

The ‘login’ worked the following way in the old application:

There were different configurations for the deployed and the local version.
The local version was using a custom form login, where the only field used for authentication was ‘username’ and the username was stored in the database with an ‘is_admin’ flag. If the user id entered was not found, then it was saved in the database, what basically means that every username is allowed and saved, but not all are admins.
The deployed version used oauth2 and the user id was taken from the properties and saved if not found in the database.

I am trying to implement the local authentication with the current versions but I am not able to get it working. I need to have a custom UsernamePasswordAuthenticationFilter implementation to set roles based on the username. I have created a filter which is called and is setting the authorities for the given user and generates a UsernamePasswordAuthenticationToken.

I am doing it the following way but the SecurityContext does not have the UsernamePasswordAuthenticationToken.

public class LocalAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

  public LocalAuthenticationFilter(UserService userService) {
    super();
    setAuthenticationManager(new LocalAuthenticationManager(userService));
  }

  public static class LocalAuthenticationManager implements AuthenticationManager {

    private final UserService userService;

    public LocalAuthenticationManager(UserService personService) {
      this.userService = personService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) {
      String username = authentication.getName();
      if (!StringUtils.hasText(username)) {
        throw new BadCredentialsException("Username is empty");
      }
      Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
      mappedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
      User user = userService.findByUid(username); // This method saves the username if not found
      if (user.isAdmin()) {
        mappedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
      }
      return new UsernamePasswordAuthenticationToken(username, "", mappedAuthorities);
    }
  }
}
@Configuration
@EnableWebSecurity
public class SecurityConfig {

  private static final String[] AUTH_ALLOWED = {
    // some allowed endpoints
  };

  private final UserService userService;

  @Autowired
  public SecurityConfig(
      UserService userService) {
    this.userService = userService;
  }

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.csrf(AbstractHttpConfigurer::disable)
        .authorizeHttpRequests(
            (authorize) ->
                authorize.requestMatchers(AUTH_ALLOWED).permitAll().anyRequest().authenticated())
        .addFilterBefore(
            new LocalAuthenticationFilter(userService), UsernamePasswordAuthenticationFilter.class)
        .formLogin(form -> form.loginPage("/").permitAll())
        .logout(LogoutConfigurer::permitAll);
    return http.build();
  }
}
@Controller
@RequestMapping("/")
public class MainController {

  @GetMapping
  public String index(Authentication authentication) {
    SecurityContext securityContext = SecurityContextHolder.getContext();

    if (authentication == null || securityContext.getAuthentication() instanceof AnonymousAuthenticationToken) {
      return "login";
    }
    return "index";
  }
}

What am I doing wrong? How should I be setting the UsernamePasswordAuthenticationToken?

4

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật