
com.luues.security.core.authentication.AuthenticationProvider Maven / Gradle / Ivy
package com.luues.security.core.authentication;
import cn.luues.tool.core.exceptions.ExceptionUtil;
import cn.luues.tool.log.Log;
import com.luues.security.core.authentication.expand.ExpandAuthenticationDetails;
import com.luues.security.core.invoke.SecurityInvoke;
import com.luues.security.core.entity.GrantedAuthority;
import com.luues.security.core.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 自定义验证登录类
* 用户名密码->(Authentication(未认证) -> AuthenticationManager ->AuthenticationProvider->UserDetailService->UserDetails->Authentication(已认证)
*/
public class AuthenticationProvider implements org.springframework.security.authentication.AuthenticationProvider {
@Autowired
private SecurityInvoke securityInvoke;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
ExpandAuthenticationDetails captchaAuthenticationDetails = (ExpandAuthenticationDetails) authentication.getDetails();
//try {
SysUser sysUser = securityInvoke.authenticate(authentication, captchaAuthenticationDetails);
List roles = securityInvoke.findUserRoles(sysUser);
List permissions = securityInvoke.findUserPermissions(sysUser);
sysUser.setPermissions(null != permissions ? permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()) : new ArrayList<>());
if (null == roles || roles.size() == 0) {
//由于权限参数不能为空,所以这里先使用AuthorityUtils.commaSeparatedStringToAuthorityList方法模拟一个admin的权限,该方法可以将逗号分隔的字符串转换为权限集合。
//数据库中的密码是加密后的
return new UsernamePasswordAuthenticationToken(sysUser, sysUser.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN"));
} else {
return new UsernamePasswordAuthenticationToken(sysUser, sysUser.getPassword(), roles.stream().map(GrantedAuthority::new).collect(Collectors.toList()));
}
/*}catch (Exception e){
if(e instanceof AuthenticationException){
throw e;
}else{
try {
throw ExceptionUtil.getRootCause(e);
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
}*/
}
@Override
public boolean supports(Class> aClass) {
//确保authentication能转成该类
return aClass.equals(UsernamePasswordAuthenticationToken.class);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy