shiro授权以及注解式开发

一、授权

1.给用户授予角色

①拿到账号

②通过用户账号拿到授予的角色

③将这些角色交给shiro进行管理

2.给用户授予权限

①拿到账号

②通过用户账号拿到能看到的授予的权限

③将这些权限交给shiro进行管理

首先在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>

 mapper文件中

Set<String> getRolesByUserId(@Param("userid") Integer userid);

Set<String> getPersByUserId(@Param("userid") Integer userid);

 service层

Set<String> getRolesByUserId(Integer userid);

Set<String> getPersByUserId(Integer userid);

myRealm文件

package com.ltf.shiro;
 
import com.ltf.model.ShiroUser;
import com.ltf.service.ShiroUserService;
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 org.springframework.stereotype.Service;
 
import java.util.Set;
 
public class MyRealm extends AuthorizingRealm {
    private ShiroUserService shiroUserService;
 
    public ShiroUserService getShiroUserService() {
        return shiroUserService;
    }
 
    public void setShiroUserService(ShiroUserService shiroUserService) {
        this.shiroUserService = shiroUserService;
    }
 
 
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("用户授权...");
        String username = principals.getPrimaryPrincipal().toString();
        ShiroUser user = shiroUserService.queryByName(username);
        Set<String> roles = shiroUserService.getRolesByUserId(user.getUserid());
        Set<String> pers = shiroUserService.getPersByUserId(user.getUserid());
 
//        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addRoles(roles);
//        info.addStringPermissions(pers);
 
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(pers);
 
        return info;
    }
 
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("身份认证...");
        String username = token.getPrincipal().toString();
        String password = token.getCredentials().toString();
        ShiroUser user = shiroUserService.queryByName(username);
//        拿到数据库中的用户信息,放入token凭证中,用于controler进行对比
        AuthenticationInfo info = new SimpleAuthenticationInfo(
                user.getUsername(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                this.getName()
        );
        return info;
    }
}

 实现类

@Override
public Set<String> getRolesByUserId(Integer userId) {
    return shiroUserMapper.getRolesByUserId(userId);
}

@Override
public Set<String> getPersByUserId(Integer userId) {
    return shiroUserMapper.getPersByUserId(userId);

 

debug运行时进入断点,可看到roles为1(普通用户)

 登录成功后进入页面

点击用户新增时会进入断点

 然后出现以下界面

返回再次点击用户新增时,又会进入断点,说明shiro每次都会进入数据库,查看你是否有权限,说明shiro的安全性极高,但是由于每次请求都要访问数据库,所以性能不好,这里可以使用redis缓存

 没有权限的原因是在applicationContext-shiro文件中配置的权限是这样的

而数据库中普通用户的id为1,所以应该将admin改为1

再次访问  就有权限了

 

二、注解式开发

常用注解介绍

@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

建立AnnotationController类

package com.ltf.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;
 
import javax.servlet.http.HttpServletRequest;
@Controller
public class AnnotationController {
    //只有登录才能访问
    @RequiresUser
    @RequestMapping("/passUser")
    public String passUser(HttpServletRequest request){
        return "admin/addUser";
    }
    //拥有roleid为1和4的角色才能访问
    @RequiresRoles(value = {"1","4"},logical = Logical.AND)
    @RequestMapping("/passRole")
    public String passRole(HttpServletRequest request){
        return "admin/listUser";
    }
    //拥有修改和查看的权限才能访问
    @RequiresPermissions(value = {"user:update","user:view"},logical = Logical.OR)
    @RequestMapping("/passPer")
    public String passPer(HttpServletRequest request){
        return "admin/resetPwd";
    }
 
    @RequestMapping("/unauthorized")
    public String unauthorized(){
        return "unauthorized";
    }
 
}

@Controller注解是为了交给spring处理

AnnotationController 是直接处理浏览器的请求,也就说明了shiro要与springMVC配合使用

也就意味着要在springMVC中进行配置

    <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>

测试代码

<%--
  Created by IntelliJ IDEA.
  User: 小宝的宝
  Date: 2021/12/17
  Time: 20:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
hello springMVC
 
<ul>
    shiro注解
    <li>
        <a href="${pageContext.request.contextPath}/passUser">用户认证</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/passRole">角色</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/passPer">权限认证</a>
    </li>
</ul>
 
</body>
</html>

运行代码

当登录后用户认证可以点击跳到

角色未授权,点击后

 因为在配置文件中配置了路径

 要想访问成功必须修改授权

 

将原本的and修改成or,普通用户也就可以访问了

权限认证需要拥有修改或查看列表的权限才可以访问

所以换个有修改的权限的用户登录就可以访问了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小宝的宝呢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值