1 | package project.educatum.config;
|
---|
2 |
|
---|
3 | import org.springframework.security.authentication.AuthenticationProvider;
|
---|
4 | import org.springframework.security.authentication.BadCredentialsException;
|
---|
5 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
---|
6 | import org.springframework.security.core.Authentication;
|
---|
7 | import org.springframework.security.core.AuthenticationException;
|
---|
8 | import org.springframework.security.core.userdetails.UserDetails;
|
---|
9 | import org.springframework.security.crypto.password.PasswordEncoder;
|
---|
10 | import org.springframework.stereotype.Component;
|
---|
11 | import project.educatum.model.exceptions.InvalidUserCredentialsException;
|
---|
12 | import project.educatum.service.AuthService;
|
---|
13 |
|
---|
14 | @Component
|
---|
15 | public class CustomAuthenticationProvider implements AuthenticationProvider {
|
---|
16 |
|
---|
17 | private final AuthService authService;
|
---|
18 | private final PasswordEncoder passwordEncoder;
|
---|
19 |
|
---|
20 | public CustomAuthenticationProvider(AuthService authService, PasswordEncoder passwordEncoder) {
|
---|
21 | this.authService = authService;
|
---|
22 | this.passwordEncoder = passwordEncoder;
|
---|
23 | }
|
---|
24 |
|
---|
25 | @Override
|
---|
26 | public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
---|
27 | String username = authentication.getName();
|
---|
28 | String password = authentication.getCredentials().toString();
|
---|
29 | if ("".equals(username) || "".equals(password)) {
|
---|
30 | throw new BadCredentialsException("Bad credentials!");
|
---|
31 | }
|
---|
32 | UserDetails userDetails = this.authService.loadUserByUsername(username);
|
---|
33 | if (!passwordEncoder.matches(password, userDetails.getPassword())) {
|
---|
34 | throw new BadCredentialsException("Bad credentials!");
|
---|
35 | }
|
---|
36 | return new UsernamePasswordAuthenticationToken(userDetails,
|
---|
37 | userDetails.getPassword(), userDetails.getAuthorities());
|
---|
38 | }
|
---|
39 |
|
---|
40 | @Override
|
---|
41 | public boolean supports(Class<?> authentication) {
|
---|
42 | return authentication.equals(CustomAuthenticationProvider.class);
|
---|
43 | }
|
---|
44 | }
|
---|