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