欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Shiro授权

程序员文章站 2022-05-19 10:11:19
...

1,shiro授权角色、权限

1.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.2 在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.3 在ShiroUserService.java中添加内容,并实现对应接口中的内容

package com.su.ssm.service;

import com.su.ssm.model.ShiroUser;

import java.util.Set;


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.su.ssm.service.impl;

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

import java.util.Set;


@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.4 重写MyRealm.java中的授权方法

package com.su.ssm.shiro;

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

/**
 * 替换了上堂课的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;
    }
}


用zmd登录点击用户新增未授权会显示如下图:
Shiro授权
授权显示如下:
Shiro授权
shiro是优缺点并存的,优点就是安全性能高,缺点就是性能低,因为每发一次请求就要做一次权限认证

2, 注解式开发

常用注解介绍

@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

注解的使用
Controller :

package com.su.ssm.controller;

import com.su.ssm.model.Book;
import com.su.ssm.service.BookService;
import com.su.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;

/**
 * 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";
    }

}

在spring-mvc.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>


@RequiresUser
只要是用户都可以访问
Shiro授权
@RequiresRoles(value = {“2”,“4”},logical = Logical.OR)
在满足注解里的要求的角色才可以访问
Shiro授权
同样也是在满足注解里的要求的权限才可以访问
zdm登录访问。如果想让另外一个也访问到那就将AND改成OR
Shiro授权

相关标签: Shiro授权