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