package com.example.autopartz.config; import com.example.autopartz.service.UserService; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import java.util.Objects; @Component public class CustomUsernamePasswordAuthenticationProvider implements AuthenticationProvider { private final UserService userService; private final PasswordEncoder passwordEncoder; public CustomUsernamePasswordAuthenticationProvider(UserService userService, PasswordEncoder passwordEncoder) { this.userService = userService; this.passwordEncoder = passwordEncoder; } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = authentication.getCredentials().toString(); if ("".equals(username) || "".equals(password)) { throw new BadCredentialsException("Invalid Credentials"); } UserDetails userDetails = this.userService.findByUsername(username); String realPassword = userDetails.getPassword(); if (!Objects.equals(password,realPassword)) { throw new BadCredentialsException("Password is incorrect!"); } return new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities()); } @Override public boolean supports(Class aClass) { return aClass.equals(UsernamePasswordAuthenticationToken.class); } }