Shiro授权

2 篇文章 0 订阅
本文详细介绍了Shiro的授权流程,包括Mapper层、Service层的配置,以及自定义Realm的实现。在授权方法部分,强调了角色与权限的匹配与配置。文章还探讨了注解式开发,讲解了Shiro的常用注解,如@RequiresAuthentication、@RequiresRoles和@RequiresPermissions,并给出了在SpringMVC中的拦截器配置及Controller层的示例。
摘要由CSDN通过智能技术生成

目录

一、shiro授权

Mapper层

 Service层 

shiro的 授权的方法 

 测试

二、注解式开发

常用注解介绍

将对应注解添加到指定需要权限控制的方法上

在springmvc-servlet.xml中添加拦截相关配置

controller层


一、shiro授权

Mapper层

UserMapper.xml中新增内容

<!--通过用户名查询对应的角色-->
<select id="selectRoleIdsByUserName" resultType="java.lang.String" parameterType="java.lang.String" >
   select ur.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.java

package com.maomao.ssm.mapper;

import com.maomao.ssm.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);
}

 Service层 

UserBiz.java

package com.maomao.ssm.biz;

import com.maomao.ssm.model.User;
import org.apache.ibatis.annotations.Param;

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

package com.maomao.ssm.biz.impl;

import com.maomao.ssm.biz.UserBiz;
import com.maomao.ssm.mapper.UserMapper;
import com.maomao.ssm.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

@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);
    }
}

shiro的 授权的方法 

MyRealm.java

package com.maomao.ssm.shiro;

import com.maomao.ssm.biz.UserBiz;
import com.maomao.ssm.model.User;
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;

public class MyRealm extends AuthorizingRealm {

    public UserBiz userBiz;

    public UserBiz getUserBiz() {
        return userBiz;
    }

    public void setUserBiz(UserBiz userBiz) {
        this.userBiz = userBiz;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = principalCollection.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 authenticationToken
     * @return
     * @throws AuthenticationException
     * shiro.ini
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = authenticationToken.getPrincipal().toString();
        User user = userBiz.queryUserByUserName(userName);
        AuthenticationInfo info=new SimpleAuthenticationInfo(
                user.getUsername(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                this.getName()//realm的名字
        );
        return info;
    }
}

角色与权限的结果要与applicationContext-shiro.xml的配置保持一致 

角色:4
权限:2

 测试

 admin的角色id是4,所有admin下的jsp界面都可以访问

admin下所有jsp界面 

 

 当登录的角色id不为4,就是没有授权,无法访问

 

  

二、注解式开发

常用注解介绍

@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

将对应注解添加到指定需要权限控制的方法上

身份认证:requireUser

角色认证:requireRole

权限认证: requirePermission

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

controller层

ShiroController.java

package com.maomao.ssm.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;

@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";
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值