Shiro 授权&注解式开发 - SSM
权限图解如下:
Shiro 授权
-
添加角色和权限的授权方法
//根据username查询该用户的所有角色,用于角色验证 Set<String> findRoles(String username); //根据username查询他所拥有的权限信息,用于权限判断 Set<String> findPermissions(String username);
-
自定义 Realm 配置 Shiro 授权认证
1) 获取验证身份(用户名) 2) 根据身份(用户名)获取角色和权限信息 3) 将角色和权限信息设置到SimpleAuthorizationInfo SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(); info.setRoles(roles); info.setStringPermissions(permissions);
-
使用 Shiro 标签实现权限验证
3.1 导入 Shiro 标签库
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
3.2 Shiro 标签库
guest标签 :验证当前用户是否为“访客”,即未认证(包含未记住)的用户 user标签 :认证通过或已记住的用户 authenticated标签 :已认证通过的用户。不包含已记住的用户,这是与user标签的区别所在 notAuthenticated标签 :未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户 principal 标签 :输出当前用户信息,通常为登录帐号信息 hasRole标签 :验证当前用户是否属于该角色 lacksRole标签 :与hasRole标签逻辑相反,当用户不属于该角色时验证通过 hasAnyRole标签 :验证当前用户是否属于以下任意一个角色 hasPermission标签 :验证当前用户是否拥有指定权限 lacksPermission标签 :与hasPermission标签逻辑相反,当前用户没有制定权限时,验证通过
在 ShiroUserMapper.xml 中新增内容
<select id="getRolesByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
select r.roleid from t_shiro_user u,t_shiro_user_role ur,t_shiro_role r
where u.userid = ur.userid and ur.roleid = r.roleid
and u.userid = #{userid}
</select>
<select id="getPersByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
select p.permission from t_shiro_user u,t_shiro_user_role ur,t_shiro_role_permission rp,t_shiro_permission p
where u.userid = ur.userid and ur.roleid = rp.roleid and rp.perid = p.perid
and u.userid = #{userid}
</select>
Service 层
ShiroUserService.java
package com.dj.ssm.service;
import com.dj.ssm.model.ShiroUser;
import java.util.Set;
public interface ShiroUserService {
public Set<String> getRolesByUserId(Integer userId);
public Set<String> getPersByUserId(Integer userId);
public ShiroUser queryByName