package com.moral.security.auth.login; import com.moral.entity.Account; import com.moral.security.model.UserContext; import com.moral.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.InsufficientAuthenticationException; 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.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.util.List; import java.util.stream.Collectors; /** * @author vladimir.stankovic *
* Aug 3, 2016
*/
@Component
public class LoginAuthenticationProvider implements AuthenticationProvider {
private final BCryptPasswordEncoder encoder;
private final AccountService accountService;
@Autowired
public LoginAuthenticationProvider(final AccountService accountService, final BCryptPasswordEncoder encoder) {
this.accountService = accountService;
this.encoder = encoder;
}
/**
* 用户名和密码认证
*
* @param authentication
* @return
* @throws AuthenticationException
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Assert.notNull(authentication, "No authentication data provided");
String accountName = (String) authentication.getPrincipal();
String password = (String) authentication.getCredentials();
LoginMode mode = (LoginMode) authentication.getDetails();
Account account = accountService.queryAccountByName(accountName).orElseThrow(() -> new UsernameNotFoundException("User not found: " + accountName));
if (!encoder.matches(password, account.getPassword())) {
throw new BadCredentialsException("Authentication Failed. Username or Password not valid.");
}
if (account.getRoles() == null) {
throw new InsufficientAuthenticationException("User has no roles assigned");
}
List