shiro授权-SSM

shiro授权角色、权限

  1. 在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>

  1. 在ShiroUserMapper.java中用set集合进行接收xml中传过来的方法
    /**
     * 查询用户对应的角色id集合
     * @param userid
     * @return
     */
    Set<String> getRolesByUserId(@Param("userid") Integer userid);

    /**
     * 查询用户对应的权限名称集合
     * @param userid
     * @return
     */
    Set<String> getPersByUserId(@Param("userid") Integer userid);

  1. 在ShiroUserService.java中添加内容,并实现对应接口中的内容
    ShiroUserService.java
package com.xfz.ssm.service;

import com.xfz.ssm.model.ShiroUser;

import java.util.Set;

/**
 * @author xfz
 * @site www.xfz.com
 * @company zking
 * @create  2019-11-30 20:24
 */
public interface ShiroUserService {
    //shiro授权
    public Set<String> getRolesByUserId(Integer userId);

    public Set<String> getPersByUserId(Integer userId);

    //shiro认证盐加密
    ShiroUser queryByName(String uname);

    int insert(ShiroUser record);
}

ShiroUserServiceImpl

package com.xfz.ssm.service.impl;

import com.xfz.ssm.mapper.ShiroUserMapper;
import com.xfz.ssm.model.ShiroUser;
import com.xfz.ssm.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author xfz
 * @site www.xfz.com
 * @company zking
 * @create  2019-11-30 20:25
 */

@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
    @Autowired
    private ShiroUserMapper shiroUserMapper;

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

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

    //shiro认证盐加密
    @Override
    public ShiroUser queryByName(String uname) {
        return shiroUserMapper.queryByName(uname);
    }

    @Override
    public int insert(ShiroUser record) {
        return shiroUserMapper.insert(record);
    }
}

  1. 在之前写过的myrealm中添加授权的方法
package com.xfz.ssm.shiro;

import com.xfz.ssm.model.ShiroUser;
import com.xfz.ssm.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.Component;

import java.util.Set;

/**
 * @author xfz
 * @site www.xfz.com
 * @company zking
 * @create  2019-11-30 19:57
 *
 * 替换了上堂课的ini文件,所有用户的身份都从这里来
 */
@Component
public class MyRealm extends AuthorizingRealm {
    private ShiroUserService shiroUserService;

    public ShiroUserService getShiroUserService() {
        return shiroUserService;
    }

    public void setShiroUserService(ShiroUserService shiroUserService) {
        this.shiroUserService = shiroUserService;
    }

    /**
     * 授权的方法
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("进行授权。。。");
        ShiroUser shiroUser = this.shiroUserService.queryByName(principals.getPrimaryPrincipal().toString());
        //当前认证过的用户对应的角色id集合
        Set<String> rolesByUserId = this.shiroUserService.getRolesByUserId(shiroUser.getUserid());
        //当前认证过的用户对应的权限id集合
        Set<String> persByUserId = this.shiroUserService.getPersByUserId(shiroUser.getUserid());
        AuthorizationInfo info=new SimpleAuthorizationInfo();
        ((SimpleAuthorizationInfo) info).setRoles(rolesByUserId);
        ((SimpleAuthorizationInfo) info).setStringPermissions(persByUserId);
        return info;
    }

    /**
     * 身份认证的方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     * token是controller层传递过来的,也就是说一做登录操作,就会访问这个方法
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String uname= (String) authenticationToken.getPrincipal().toString();
        String pwd= (String) authenticationToken.getCredentials().toString();
        ShiroUser shiroUser = shiroUserService.queryByName(uname);
        AuthenticationInfo info=new SimpleAuthenticationInfo(
                shiroUser.getUsername(),
                shiroUser.getPassword(),
                ByteSource.Util.bytes(shiroUser.getSalt()),
                this.getName()
        );
        return info;
    }
}

shiro授权最大的优点是安全性非常高,同时也是缺点,性能会降低,因为每发一个请求都会去做一次权限认证
在这里插入图片描述

在这里插入图片描述

注解式开发

常用注解介绍

  1. @RequiresAuthenthentication:表示当前Subject已经通过login进行身份验证;即 Subject.isAuthenticated()返回 true
  2. @RequiresUser:表示当前Subject已经身份验证或者通过记住我登录的
  3. @RequiresGuest:表示当前Subject没有身份验证或者通过记住我登录过,即是游客身份
  4. @RequiresRoles(value = {“admin”,“user”},logical = Logical.AND):表示当前Subject需要角色admin和user
  5. @RequiresPermissions(value = {“user:delete”,“user:b”},logical = Logical.OR):表示当前Subject需要权限user:delete或者user:b

注解的使用
Controller

package com.xfz.ssm.controller;

import com.xfz.ssm.model.Book;
import com.xfz.ssm.service.BookService;
import com.xfz.ssm.util.PageBean;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xfz
 * @site www.xfz.com
 * @company zking
 * @create  2019-11-22 11:39
 *
 * springmvc 中五种返回值处理情况
 * 转发3种
 * 转发到安全目录web-inf下
 * 转发到根目录下
 * 转发到requestMapping
 *
 *重定向2种
 * 根目录
 * requestMapping
 */
@Controller
public class HelloController {
    @Autowired
    private BookService bookService;

    @RequestMapping("/say1")
    public String say1() {
        return "hello";
    }

    public ModelAndView say2() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/hello2");
        mv.addObject("msg", "略略略");
        return mv;
    }

    //    转发到安全目录web-inf下
    @RequestMapping("/req1")
    public String req1() {
        System.out.println("转发到安全目录web-inf下...");
        return "abc";
    }

    //    转发到根目录下
    @RequestMapping("/req2")
    public String req2() {
        System.out.println("转发到根目录下...");
        return "forward:/cba.jsp";
    }

    //    转发到requestMapping
    @RequestMapping("/req3")
    public String req3() {
        System.out.println("转发到requestMapping...");
        return "forward:/req2";
    }

    //    根目录
    @RequestMapping("/red1")
    public String red1() {
        System.out.println("red1根目录...");
        return "redirect:/bca.jsp";
    }

    //    requestMapping
    @RequestMapping("/red2")
    public String red2() {
        System.out.println("red1根目录...");
        return "redirect:/req2";
    }

    //map集合里面套了list
    @ResponseBody
    @RequestMapping("/json1")
    public Map json1(HttpServletRequest req) {
        //之前的用法
//        ObjectMapper om=new ObjectMapper();
//        String s = om.writeValueAsString("这里既可以放map,也可以放list,也可以放字符串");
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List<Map> list = bookService.listPager(new Book(), pageBean);
        Map map = new HashMap();
        map.put("total", 101);
        map.put("data", list);
        return map;
    }

    //直接是list
    @ResponseBody
    @RequestMapping("/json2")
    public List<Map> json2(HttpServletRequest req) {
        //之前的用法
//        ObjectMapper om=new ObjectMapper();
//        String s = om.writeValueAsString("这里既可以放map,也可以放list,也可以放字符串");
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List<Map> list = bookService.listPager(new Book(), pageBean);

        return list;
    }

    //字符串
    @ResponseBody
    @RequestMapping("/json3")
    public String json3(HttpServletRequest req) {
        return "springmvc string to json";
    }



//注解式开发
    @RequiresUser
    @ResponseBody
    @RequestMapping("/passUser")
    public String passUser(HttpServletRequest req) {
        return "pass user";
    }

    @RequiresRoles(value = {"2","4"},logical = Logical.OR)
    @ResponseBody
    @RequestMapping("/passRole")
    public String passRole(HttpServletRequest req) {
        return "pass role";
    }

    @RequiresPermissions(value = {"user:load","user:export"},logical = Logical.AND)
    @ResponseBody
    @RequestMapping("/passAuth")
    public String passAuth(HttpServletRequest req) {
        return "pass auth";
    }

}

@RequiresUser
只要是用户都可以访问
在这里插入图片描述

@RequiresRoles(value = {“2”,“4”},logical = Logical.OR)
在满足注解里的要求的角色才可以访问
不符合要求:在这里插入图片描述
符合要求:在这里插入图片描述

@RequiresPermissions(value = {“user:load”,“user:export”},logical = Logical.AND)
同样也是在满足注解里的要求的权限才可以访问
zdm登录访问。如果想让另外一个也访问到那就将AND改成OR
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值