SpringSecurity实现自定义登录认证、权限验证、鉴权

本文介绍了如何使用SpringSecurity实现自定义登录认证和权限验证。通过实现UserDetails、UserDetailsService和AuthenticationProvider接口完成登录认证,利用AccessDecisionManager、FilterInvocationSecurityMetadataSource和AbstractSecurityInterceptor进行权限验证。此外,还提到了配置类WebSecurityConfigurerAdapter在OAuth2认证中的应用。
摘要由CSDN通过智能技术生成

Demo源码:https://github.com/ygsama/ipa

自定义登录认证的实现

需要实现三个接口
UserDetails 用户类接口
UserDetailsService 查询用户密码的service 接口
AuthenticationProvider 为认证管理器AuthenticationManager 提供验证组件AuthenticationProvider

/**
 * 实现了 {@link UserDetails}接口
 * 用于构建存储在SecurityContextHolder的Authentication对象
 *
 * @author ygsama
 */
@Slf4j
@Data
public class SysUserDO implements UserDetails {
   

	private String username;

	private String password;

	private String name;

	private List<SysRoleDO> roleList;

	// ... 其他字段省略

	/**
	 * 装填用户的角色列表
	 */
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
   
		if (roleList == null || roleList.size() < 1) {
   
			return AuthorityUtils.commaSeparatedStringToAuthorityList("");
		}
		log.info("[原始用户角色列表装填]: ", roleList);
		StringBuilder roles = new StringBuilder();
		for (SysRoleDO role : roleList) {
   
			roles.append("ROLE_").append(role.getNo()).append(",");
		}
		List<GrantedAuthority> authorityList = AuthorityUtils.commaSeparatedStringToAuthorityList(roles.substring(0, roles.length() - 1));
		log.info("[遍历并返回用户的角色列表]: {}", authorityList);
		return authorityList;
	}

	@Override
	public String getPassword() {
   
		return this.password;
	}

	@Override
	public String getUsername() {
   
		return this.username;
	}

	@Override
	public boolean isAccountNonExpired() {
   
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
   
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
   
		return true;
	}

	@Override
	public boolean isEnabled() {
   
		return true;
	}

}
/**
 * 用户登录的service实现类 <br>
 * 框架的默认实现是{@link JdbcDaoImpl} <br>
 *
 * @author ygsama
 */
@Slf4j
@Service("userDetailsService")
public class LoginUserDetailsServiceImpl implements UserDetailsService {
   

	private final AuthUserMapper authUserMapper;
	private final AuthRoleMapper authRoleMapper;

	@Autowired
	public LoginUserDetailsServiceImpl(AuthUserMapper authUserMapper, AuthRoleMapper authRoleMapper) {
   
		this.authUserMapper = authUserMapper;
		this.authRoleMapper = authRoleMapper;
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
   
		SysUserDO sysUserDO = authUserMapper.selectByPrimaryKey(username)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值