[ae042f4] | 1 | package com.example.autopartz.config;
|
---|
| 2 |
|
---|
| 3 | import com.example.autopartz.service.UserService;
|
---|
| 4 | import org.springframework.security.authentication.AuthenticationProvider;
|
---|
| 5 | import org.springframework.security.authentication.BadCredentialsException;
|
---|
| 6 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
---|
| 7 | import org.springframework.security.core.Authentication;
|
---|
| 8 | import org.springframework.security.core.AuthenticationException;
|
---|
| 9 | import org.springframework.security.core.userdetails.UserDetails;
|
---|
| 10 | import org.springframework.security.crypto.password.PasswordEncoder;
|
---|
| 11 | import org.springframework.stereotype.Component;
|
---|
| 12 |
|
---|
| 13 | import java.util.Objects;
|
---|
| 14 |
|
---|
| 15 | @Component
|
---|
| 16 | public class CustomUsernamePasswordAuthenticationProvider implements AuthenticationProvider {
|
---|
| 17 |
|
---|
| 18 | private final UserService userService;
|
---|
| 19 | private final PasswordEncoder passwordEncoder;
|
---|
| 20 |
|
---|
| 21 | public CustomUsernamePasswordAuthenticationProvider(UserService userService, PasswordEncoder passwordEncoder) {
|
---|
| 22 | this.userService = userService;
|
---|
| 23 | this.passwordEncoder = passwordEncoder;
|
---|
| 24 | }
|
---|
| 25 |
|
---|
| 26 | @Override
|
---|
| 27 | public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
---|
| 28 | String username = authentication.getName();
|
---|
| 29 | String password = authentication.getCredentials().toString();
|
---|
| 30 |
|
---|
| 31 | if ("".equals(username) || "".equals(password)) {
|
---|
| 32 | throw new BadCredentialsException("Invalid Credentials");
|
---|
| 33 | }
|
---|
| 34 |
|
---|
| 35 | UserDetails userDetails = this.userService.findByUsername(username);
|
---|
| 36 | String realPassword = userDetails.getPassword();
|
---|
| 37 | if (!Objects.equals(password,realPassword)) {
|
---|
| 38 | throw new BadCredentialsException("Password is incorrect!");
|
---|
| 39 | }
|
---|
| 40 | return new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
|
---|
| 41 |
|
---|
| 42 | }
|
---|
| 43 |
|
---|
| 44 | @Override
|
---|
| 45 | public boolean supports(Class<?> aClass) {
|
---|
| 46 | return aClass.equals(UsernamePasswordAuthenticationToken.class);
|
---|
| 47 | }
|
---|
| 48 | }
|
---|
| 49 |
|
---|