一:mapper包下建立UserMapper接口并建立对应的sql映射文件UserMapper.xml
package com.xhc.mapper;
import com.xhc.domain.Permission;
import com.xhc.domain.User;
import java.util.List;
public interface UserMapper {
/**
* 查询当前用户对象
*/
public User findByUsername(String username);
/**
* 查询当前用户拥有的权限
*/
public List<Permission> findPermissionByUsername(String username);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xhc.mapper.UserMapper">
<!-- 查询用户 -->
<select id="findByUsername" parameterType="string" resultType="user">
select * from sys_user where username = #{value}
</select>
<!-- 查询用户的权限 -->
<select id="findPermissionByUsername" parameterType="string" resultType="permission">
select permission.*
from
sys_user user
inner join sys_user_role user_role on user.id = user_role.user_id
inner join sys_role_permission role_permission on user_role.role_id = role_permission.role_id
inner join sys_permission permission on role_permission.perm_id = permission.id
where user.username = #{value};
</select>
</mapper>
二:建立MyUserDetailService,从数据库中动态读取权限信息
新建一个包在com.xhc.security,在该包下创建一个类,MyUserDetailService,实现UserDetailsService。
package com.xhc.security;
import com.xhc.domain.Permission;
import com.xhc.domain.User;
import com.xhc.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.ArrayList;
import java.util.List;
/**
* 自定义UserDetailService,实现UserDetailsService接口
*/
public class MyUserDetailService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.findByUsername(username);
if (user != null) {
// 根据用户名查询用户的信息
List<Permission> list = userMapper.findPermissionByUsername(username);
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Permission permission : list) {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getPermTag());
authorities.add(grantedAuthority);
}
user.setAuthorities(authorities);
}
return user;
}
}
修改spring-security.xml文件
<security:intercept-url pattern="/goods/add" access="hasRole('ROLE_ADD_GOODS')"/> <security:intercept-url pattern="/goods/list" access="hasRole('ROLE_LIST_GOODS')"/> <security:intercept-url pattern="/goods/delete" access="hasRole('ROLE_DELETE_GOODS')"/> <security:intercept-url pattern="/goods/update" access="hasRole('ROLE_UPDATE_GOODS')"/>
启动项目,分别使用两个账户进行登录,会发现有权限的才能访问,没有权限的无法访问。