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