Last active
February 21, 2024 10:19
-
-
Save abhijeetchopra05/f2432ba5ddd35510eb0137fdbf4498d6 to your computer and use it in GitHub Desktop.
SpringSecurity Custom AuthenticationManager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks bro