Skip to content

Instantly share code, notes, and snippets.

@abhijeetchopra05
Last active February 21, 2024 10:19
Show Gist options
  • Save abhijeetchopra05/f2432ba5ddd35510eb0137fdbf4498d6 to your computer and use it in GitHub Desktop.
Save abhijeetchopra05/f2432ba5ddd35510eb0137fdbf4498d6 to your computer and use it in GitHub Desktop.
SpringSecurity Custom AuthenticationManager
package com.personal.banking.config;
import com.personal.banking.domain.Role;
import com.personal.banking.domain.User;
import com.personal.banking.repo.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class CustomAuthenticationManager implements AuthenticationManager {
@Autowired
UserRepo userRepo;
@Autowired
PasswordEncoder passwordEncoder;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Optional<User> user = userRepo.findByUserName(authentication.getName());
if (user.isPresent()) {
if (passwordEncoder.matches(authentication.getCredentials().toString(), user.get().getPassword())) {
List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
for (Role role : user.get().getRoleSet()) {
grantedAuthorityList.add(new SimpleGrantedAuthority(role.getName()));
}
return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorityList);
} else {
throw new BadCredentialsException("Wrong Password");
}
} else {
throw new BadCredentialsException("Wrong UserName");
}
}
}
@DEveL0perLuckY
Copy link

thanks bro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment