source: src/main/java/com/example/autopartz/config/CustomUsernamePasswordAuthenticationProvider.java

main
Last change on this file was ae042f4, checked in by andrejtodorovski <82031894+andrejtodorovski@…>, 23 months ago

Configured spring security, changed spring version

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