Shiro框架的四种权限控制方式

在自定义的realm中进行权限控制

  1. 在shiro-config.xml追加/user/delete = perms["delete"]


    
    
        
    
        
        
        
        
        
        
        
            
                
                
                /login.jsp = anon
                /test/login = anon
                /user/delete = perms["delete"]
                /logout = logout
                
                /** = authc
            
        
    

此时访问/user/delete需要delete权限,在自定义Realm中为用户授权。


@Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        User user = new User();
        user.setUsername(username);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //为用户授权,只需将用户的权限添加到info即可
        info.addStringPermission("delete");
        List roleList = userService.getRole(user);
        if(roleList != null){
            for (Role role : roleList) {
                authorizationInfo.addRole(role.getName());
            }
            return authorizationInfo;
        }
        return null;
    }
##使用shiro注解为用户授权 1. 在shiro-config.xml开启shiro注解(硬编码,不好用)

  
      
          


2. 在service方法上配置注解@RequiresPermissions(“user:delete”)

    @RequiresPermissions("user:delete")
    public void delete(){
        //逻辑代码
    }

使用shiro标签进行权限控制

  1. 在jsp页面引入shiro标签库
    <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
  2. 在页面中使用标签

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>




Insert title here



${successMsg } Welcome! 


User Page

Admin Page

Logout

编程方式实现用户权限控制


    Subject subject = SecurityUtils.getSubject();
    if(subject.hasRole("admin")){
        //有权限
    }else{
        //无权限
    }

你可能感兴趣的:(Shrio)