1 | package com.example.demo.config;
|
---|
2 |
|
---|
3 | import com.example.demo.repository.UserRepository;
|
---|
4 | import com.example.demo.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 |
|
---|
12 |
|
---|
13 | import org.springframework.security.crypto.password.PasswordEncoder;
|
---|
14 | import org.springframework.stereotype.Component;
|
---|
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 | UserDetails userDetails = this.userService.loadUserByUsername(username);
|
---|
36 | if(passwordEncoder.matches(password,userDetails.getPassword()))
|
---|
37 | {
|
---|
38 | throw new BadCredentialsException("Invalid Credentials");
|
---|
39 | }
|
---|
40 | return new UsernamePasswordAuthenticationToken(userDetails,userDetails.getPassword(),
|
---|
41 | userDetails.getAuthorities());
|
---|
42 |
|
---|
43 | }
|
---|
44 |
|
---|
45 | @Override
|
---|
46 | public boolean supports(Class<?> aClass) {
|
---|
47 | return aClass.equals(UsernamePasswordAuthenticationToken.class);
|
---|
48 | }
|
---|
49 | }
|
---|