source: src/main/java/com/example/moviezone/config/CustomUsernamePasswordAuthenticationProvider.java@ eb36f39

Last change on this file since eb36f39 was ac25203, checked in by DenicaKj <dkorvezir@…>, 22 months ago

Spring Security

  • Property mode set to 100644
File size: 2.0 KB
Line 
1package com.example.moviezone.config;
2
3
4import com.example.moviezone.service.UserService;
5import org.springframework.security.authentication.AuthenticationProvider;
6import org.springframework.security.authentication.BadCredentialsException;
7import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
8import org.springframework.security.core.Authentication;
9import org.springframework.security.core.AuthenticationException;
10import org.springframework.security.core.userdetails.UserDetails;
11import org.springframework.security.crypto.password.PasswordEncoder;
12import org.springframework.stereotype.Component;
13import java.util.Objects;
14
15
16@Component
17public 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,realPassword)) {
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}
Note: See TracBrowser for help on using the repository browser.