Onomatopoeia-back/src/main/java/com/example/onomatopoeiaback/security/CustomAuthenticationProvider.java

44 lines
1.9 KiB
Java

package com.example.onomatopoeiaback.security;
import com.example.onomatopoeiaback.exceptions.BadRequestException;
import com.example.onomatopoeiaback.exceptions.ForbiddenException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
final
CustomEmployeeDetailsService customEmployeeDetailsService;
final PasswordEncoder passwordEncoder;
public CustomAuthenticationProvider(CustomEmployeeDetailsService customEmployeeDetailsService, PasswordEncoder bCryptPasswordEncoder, PasswordEncoder passwordEncoder) {
this.customEmployeeDetailsService = customEmployeeDetailsService;
this.passwordEncoder = passwordEncoder;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String login = authentication.getName();
String password = passwordEncoder.encode((String) authentication.getCredentials());
if (login == null || password == null) {
throw new BadRequestException();
}
CustomEmployeeDetails customEmployeeDetails = customEmployeeDetailsService.loadUserByUsername(login);
if (customEmployeeDetails == null || !customEmployeeDetails.getPassword().equals(password)) {
throw new ForbiddenException();
}
return new UsernamePasswordAuthenticationToken(customEmployeeDetails, null, customEmployeeDetails.getAuthorities());
}
@Override
public boolean supports(Class<?> authentication) {
return false;
}
}