前言
要想实现动态配置URL权限,就要自定义权限配置
数据库
那总的来说,大概是怎么一个流程呢?
首先先创建对应数据表Bean
创建Bean
public class Role {
private Integer id;
private String name;
private String nameZh;
//省略getter setter
}
public class Menu {
private Integer id;
private String pattern;
private List<Role> roles;
//省略gettet setter
}
public class User implements UserDetails {
private Integer id;
private String username;
private String password;
private Boolean enabled;
private Boolean locked;
private List<Role> roles;
/*
这里装着该用户拥有的角色,一般情况,每一个用户都有对应一个或者几个角色,当然一开始时空的,所以要去数据库查询,并赋值给这个集合, 方便security进行比对判断。
*/
/**
* 获取登录过后用户所拥有的角色信息
* @return 角色信息集合
*/
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
//role集合不能直接给security拿去用,所以创建他能用的对象的集合,将roles集合里的对象放进去
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for (Role r : roles){
authorities.add(new SimpleGrantedAuthority(r.getName()));
}
return authorities;
}
@Override
public String getPassword() {
return password; //这里的密码会给security来比对前端传过来的密码
}
@Override
public String getUsername() {
return username;
}
/**
* 账户是否未过期
* @return 返回enable属性
*/
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return !locked;
}
/**
* 密码是否未过期
* @return Boolean
*/
@Override
public boolean isCredentialsNonExpired() {
return true;
}
/**
* 账户是否可用
* @return
*/
@Override
public boolean isEnabled() {
return enabled;
}
//省略getter setter
}
创建持久层接口
MenuMapper.xml
这个mapper的getAllMeus方法用来获取每一个url对应需要的一个或几个角色
<mapper namespace="pljandsyx.top.securitydy.mapper.MenuMapper">
<resultMap id="BaseResultMap" type="pljandsyx.top.securitydy.bean.Menu">
<id property="id" column="id"/>
<result property="pattern" column="pattern"/>
<collection property="roles" ofType="pljandsyx.top.securitydy.bean.Role">
<id property="id" column="rid"/>
<result property="name" column="rname"/>
<result property="nameZh" column="rnameZh"/>
</collection>
</resultMap>
<select id="getAllMeus" resultMap="BaseResultMap">
SELECT
m.* , r.id AS rid ,r.`name` AS rname , r.nameZh AS rnameZh
FROM
menu as m
LEFT JOIN
menu_role as mr ON m.id = mr.mid
LEFT JOIN
role as r ON r.id = mr.rid
</select>
</mapper>
MenuMapper.java
@Repository
public interface MenuMapper {
List<Menu> getAllMeus();
}
UserMapper.xml
这个方法就个就更简单了,根据用户的id获取用户所具有的角色
<mapper namespace="pljandsyx.top.securitydy.mapper.UserMapper">
<select id="loadUserByUsername" parameterType="String" resultType="pljandsyx.top.securitydy.bean.User">
select * from user where username= #{username}
</select>
<select id="getRoleById" parameterType="Integer" resultType="pljandsyx.top.securitydy.bean.Role">
select * from role where id in (select rid from user_role where uid = #{id})
</select>
</mapper>
UserMapper.java
@Repository
public interface UserMapper {
User loadUserByUsername(String username);
List<Role> getRoleById(Integer id);
}
创建Service层
UserService:
@Service
public class UserService implements UserDetailsService {
@Autowired
UserMapper userMapper;
/**
* 验证用户,登录的时候用到
* @param username 表单输入的用户名
* @return 返回user对象
* @throws UsernameNotFoundException 用户不存在异常
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.loadUserByUsername(username);//查询用户是否存在,同时查出来的用户是带有加密的密码,后面会配置securityConfig来比对前端传来的密码以及配置加密规则
if (user==null){
throw new UsernameNotFoundException("用户不存在");
}
user.setRoles(userMapper.getRoleById(user.getId()));//给查询到的用户赋予查询到的他应有的角色
return user;
}
}
MenuService
@Service
public class MenuService{
@Autowired
MenuMapper menuMapper;
public List<Menu> getAllMeus(){
List<Menu> menuList = menuMapper.getAllMeus();
return menuList;
}
}
配置
创建实现AccessDecisionManager接口的实现类CustomAccessDecisionManager:
该实现类的decide()根据当前登录用户的角色信息,跟访问当前URL所需要的角色进行对比
@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {
/**
* 该方法判断当前登录用户是否具备角色信息
* @param authentication 当前登录用户的信息
* @param o FilterInvocation对象,可以获得请求对象
* @param collection FilterInvocationSecurityMetadataSourceImpl类中获取的-》当前URL需要的角色信息
* @throws AccessDeniedException 不具备角色信息
* @throws InsufficientAuthenticationException
*/
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();//获取当前登录用户的角色信息
for (ConfigAttribute configAttribute : collection){//遍历当前URL需要的角色信息
//如果此URL需要"ROLE_login角色,并且用户已经登陆才,放行"
if ("ROLE_login".equals(configAttribute.getAttribute()) && authentication instanceof UsernamePasswordAuthenticationToken){
//空返回,跳出方法
return;
}
//遍历当前登录用户的角色信息,如果有与所需角色信息时,跳出判断
for (GrantedAuthority authority : authorities){
if (configAttribute.getAttribute().equals(authority.getAuthority())){
return;
}
}
}
//判断失败,抛出异常
throw new AccessDeniedException("权限不足");
}
@Override
public boolean supports(ConfigAttribute configAttribute) {
return true;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
创建实现FilterInvocationSecurityMetadataSource接口的实现类FilterInvocationSecurityMetadataSourceImpl,实现类最重要的方法是getAttributes(),用获取当前URL访问所需要的角色集合
@Component
public class FilterInvocationSecurityMetadataSourceImpl implements FilterInvocationSecurityMetadataSource {
//用来实现ant风格的URL匹配
AntPathMatcher antPathMatcher = new AntPathMatcher();
@Autowired
MenuService menuService;
/**
* 返回当前URL访问所需要的角色信息
* @param o 该参数是FilterInvocation ,可以用来获取URL
* @return Collection<ConfigAttribute> 表示当前请求URL所需要的角色
* @throws IllegalArgumentException
*/
@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
String requestUrl = ((FilterInvocation) o).getRequestUrl(); //获取请求URL
List<Menu> allMeus = menuService.getAllMeus();//从数据库中获取所有匹配规则
for (Menu menu : allMeus){//遍历所有的匹配规则
if (antPathMatcher.match(menu.getPattern(),requestUrl)){//如果与当前的URL与匹配规则符合
List<Role> roleList = menu.getRoles();//获取访问URL所需要的角色
String[] roles =new String[roleList.size()];//创建存储所需要角色的数据
for (int i = 0; i < roleList.size(); i++) {//遍历数组并将刚才所需要的角色存入数组
roles[i] = roleList.get(i).getName();
}
return SecurityConfig.createList(roles);//返回数组
}
}
//如果遍历所有menu后依然没有匹配到规则,那么就直接返回"ROLE_login";也就是登录了就可以访问的标志
return SecurityConfig.createList("ROLE_login");
}
/**
* 返回所有定义好的权限资源,如果不需要检验直接返回null即可
* @return
*/
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
/**
* 返回 类对象是否支持校验
* @param aClass
* @return
*/
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
最后在SpringSecurity配置文件注入配置
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Autowired
FilterInvocationSecurityMetadataSourceImpl filterInvocationSecurityMetadataSource;
@Autowired
CustomAccessDecisionManager customAccessDecisionManager;
/**
* 加密
* @return
*/
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
/**
* 注入配置好UserService验证
* @param auth 角色验证
* @throws Exception 捕捉任何异常
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O o) {
o.setSecurityMetadataSource(filterInvocationSecurityMetadataSource);
o.setAccessDecisionManager(customAccessDecisionManager);
return o;
}
})
.and()
.formLogin()
.permitAll()
.and()
.csrf()
.disable();
}
}
踩坑:
User类里没有成功获取roles集合信息,导致后续权限判断失败,(返回的authorities.size()为0),
这里注意导入的Role类是你的自定义Bean,有一个系统Role类,导错包。
/**
* 获取登录过后用户所拥有的角色信息
* @return 角色信息集合
*/
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for (Role r : roles){
authorities.add(new SimpleGrantedAuthority(r.getName()));
}
return authorities;
}
笔记