目录
一、Shiro授权
授角色:用户具备哪些角色
SELECT roleid from t_shiro_user u,t_shiro_user_role ur
where u.userid = ur.userid and u.username = 'zdm'
授权限:用户具备哪些权限
SELECT rp.perid from t_shiro_user u, t_shiro_user_role ur,t_shiro_role_permission rp
where u.userid = ur.userid and ur.roleid= rp.roleid and u.username = 'ww
步骤:
1、Mapper层、service层
UserMapper.xml:
<select id="selectRoleIdsByUserName" resultType="java.lang.String" parameterType="java.lang.String" >
SELECT roleid from t_shiro_user u,t_shiro_user_role ur
where u.userid = ur.userid and u.username = #{userName}
</select>
<select id="selectPerIdsByUserName" resultType="java.lang.String" parameterType="java.lang.String" >
SELECT rp.perid from t_shiro_user u, t_shiro_user_role ur,t_shiro_role_permission rp
where u.userid = ur.userid and ur.roleid= rp.roleid and u.username = #{userName}
</select>
UserMapper :
package com.ycx.mapper;
import com.ycx.model.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.Set;
@Repository
public interface UserMapper {
int deleteByPrimaryKey(Integer userid);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer userid);
//通过账户名查询账户信息
User queryUserByUserName (@Param("userName") String userName);
//通过账户名查询对应的角色
Set<String> selectRoleIdsByUserName (@Param("userName") String userName);
//通过账户名查询对应的权限
Set<String> selectPerIdsByUserName (@Param("userName") String userName);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
UserBiz :
package com.ycx.ssm.biz;
import com.ycx.model.User;
import java.util.Set;
public interface UserBiz {
int deleteByPrimaryKey(Integer userid);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer userid);
User queryUserByUserName(String userName);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
//通过账户名查询对应的角色
Set<String> selectRoleIdsByUserName (String userName);
//通过账户名查询对应的权限
Set<String> selectPerIdsByUserName (String userName);
}
UserBizImpl :
package com.ycx.ssm.biz.impl;
import com.ycx.mapper.UserMapper;
import com.ycx.model.User;
import com.ycx.ssm.biz.UserBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
/**
* @author 杨总
* @create 2022-08-25 19:17
*/
@Service("userBiz")
public class UserBizImpl implements UserBiz {
@Autowired
private UserMapper userMapper;
@Override
public int deleteByPrimaryKey(Integer userid) {
return userMapper.deleteByPrimaryKey(userid);
}
@Override
public int insert(User record) {
return userMapper.insert(record);
}
@Override
public int insertSelective(User record) {
return userMapper.insertSelective(record);
}
@Override
public User selectByPrimaryKey(Integer userid) {
return userMapper.selectByPrimaryKey(userid);
}
@Override
public User queryUserByUserName(String userName) {
return userMapper.queryUserByUserName(userName);
}
@Override
public int updateByPrimaryKeySelective(User record) {
return userMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(User record) {
return userMapper.updateByPrimaryKeySelective(record);
}
@Override
public Set<String> selectRoleIdsByUserName(String userName) {
return userMapper.selectRoleIdsByUserName(userName);
}
@Override
public Set<String> selectPerIdsByUserName(String userName) {
return userMapper.selectPerIdsByUserName(userName);
}
}
MyRealm :
package com.ycx.shiro;
import com.ycx.model.User;
import com.ycx.ssm.biz.UserBiz;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import java.util.Set;
/**
* @author 杨总
* @create 2022-08-25 19:38
*/
public class MyRealm extends AuthorizingRealm {
public UserBiz userBiz;
public UserBiz getUserBiz() {
return userBiz;
}
public void setUserBiz(UserBiz userBiz) {
this.userBiz = userBiz;
}
/**
* 授权
* @param principals
* @return
* shiro-web.ini
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String userName = principals.getPrimaryPrincipal().toString();//获取账户名
Set<String> roleIds = userBiz.selectRoleIdsByUserName(userName);
Set<String> perIds = userBiz.selectPerIdsByUserName(userName);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 将当前登录的权限交给shiro的授权器
info.setStringPermissions(perIds);
// 将当前登录的角色交给shiro的授权器
info.setRoles(roleIds);
return info;
}
/**
* 认证
* @param token
* @return
* @throws AuthenticationException
* shiro.ini
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName = token.getPrincipal().toString();
User user = null;
try {
user = userBiz.queryUserByUserName(userName);
}catch (Exception e){
e.printStackTrace();
}
AuthenticationInfo info=new SimpleAuthenticationInfo(
user.getUsername(),
user.getPassword(),
ByteSource.Util.bytes(user.getSalt()),
this.getName()//realm的名字
);
return info;
}
}
2、shiro 的 授权方式
注意:角色与权限的结果要与spring-shiro.xml的配置保持一致
角色:1,4
权限:1,2
3、测试
二、shiro注解式开发
常用注解介绍:
@RequiresAuthenthentication:表示当前Subject已经通过login进行身份验证;即 Subject.isAuthenticated()返回 true
@RequiresUser:表示当前Subject已经身份验证或者通过记住我登录的
@RequiresGuest:表示当前Subject没有身份验证或者通过记住我登录过,即是游客身份
@RequiresRoles(value = {"admin","user"},logical = Logical.AND):表示当前Subject需要角色admin和user
@RequiresPermissions(value = {"user:delete","user:b"},logical = Logical.OR):表示当前Subject需要权限user:delete或者user:b
1)将对应注解添加到指定需要权限控制的方法上
身份认证:requireUser
角色认证:requireRole
权限认证: requirePermission
(2)在SpringMVC.xml中添加拦截相关配置
controller层
ShiroController :
package com.ycx.controller;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author 杨总
* @create 2022-08-26 20:22
*/
@RequestMapping("/shiro")
@Controller
public class ShiroController {
// RequiresUser代表 当前方法只有登录后才能够访问
// RequiresUser等价于spring-shiro.xml中的/user/updatePwd.jsp=authc配置
@RequiresUser
@RequestMapping("/passUser")
public String passUser(){
System.out.println("身份认证通过!");
return "admin/addUser";
}
//RequiresRoles 代表当前方法只有具备指定的角色才能访问
// RequiresRoles等价于spring-shiro.xml中的/admin/*.jsp=roles[4]配置
@RequiresRoles(value = {"1","4"},logical = Logical.AND)
@RequestMapping("/passRole")
public String passRole(){
System.out.println("角色认证通过!");
return "admin/addUser";
}
//RequiresRoles 代表当前方法只有具备指定的权限才能访问
// RequiresRoles等价于spring-shiro.xml中的/user/teacher.jsp=perms[2]配置
@RequiresPermissions(value = {"2"},logical = Logical.AND)
@RequestMapping("/passPermission")
public String passPermission(){
System.out.println("权限认证通过!");
return "admin/addUser";
}
}
Springmvc-servlet.xml:
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true"></property>
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.apache.shiro.authz.UnauthorizedException">
unauthorized
</prop>
</props>
</property>
<property name="defaultErrorView" value="unauthorized"/>
</bean>
再输入地址栏 http://localhost:8080/shiro/passUser:
进入成功
再输入地址栏 http://localhost:8080/shiro/passRole :
再切换ls登录:
登录进去之后:
再输入地址栏 http://localhost:8080/shiro/passRole :
错误又不一样了.
如果换zdm登录:
进入之后再输入地址栏 http://localhost:8080/shiro/passRole :
可进行访问。
退出再次登录zs,然后地址栏输入http://localhost:8080/shiro/passPermission:
显示没有权限2.
而登录ls,再次输入:
则有用户新增。
如果把AND改为OR:
再次登录zs时,/shiro/passRole
之前是不可访问的,现在可访问了。