shiro授权和注解式开发

shiro授权

shiro完成登录的流程:首先是我们前端输入用户名和密码,跳转到Controller然后生成token之后进行认证,我们根据用户名拿到这个用户的所有信息(主要是盐和MD5加密后的密码)然后判断通过,在跳转到前端之前又进行授权验证,看看这个用户是否拥有权限进入jsp,这就是我们今天要做的事情

一个完整的权限是五张表构成
在这里插入图片描述
既然我们需要进行权限认证,首先我们需要根据用户id获取他的角色(role)和权限(pers),所以需要写两个查询的方法

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>

ShiroUserMapper

    Set<String> getRolesByUserId(Integer userId);

    Set<String> getPersByUserId(Integer userName);

然后分别在service层中实现就好,然后在我们自己写的realm中调用方法验证
MyRealm

package com.xy.shiro;

import com.xy.model.ShiroUser;
import com.xy.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 java.util.Set;

/**
 * @author 阳某
 * @create 2019-10-13 16:13
 *
 */
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) {
        String username = principals.getPrimaryPrincipal().toString();//获取用户名
        ShiroUser shiroUser = shiroUserService.queryByName(username);//根据用户名获取用户信息
        Set<String> pers = shiroUserService.getPersByUserId(shiroUser.getUserid());//根据uid获取权限
        Set<String> roles = shiroUserService.getRolesByUserId(shiroUser.getUserid());//根据uid获取角色
//        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addRoles(roles);
//        info.addStringPermissions(pers);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(pers);

        return info;
    }

    /**
     * 认证
     *
     * 认证的过程
     * 1、数据源(ini)现在数据库
     * 2、doGetAuthenticationInfo将数据库的用户信息给subject主体做shiro认证
     *  2.1、需要在当前realm中调用service来验证,当前用户是要有在数据库中存在
     *  2.2、盐加密
     *
     * @param token   从jsp传递过来的用户名密码组成的一个token对象
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = token.getPrincipal().toString();
        String pwd = token.getCredentials().toString();
        ShiroUser shiroUser = this.shiroUserService.queryByName(userName);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                shiroUser.getUsername(),
                shiroUser.getPassword(),
                ByteSource.Util.bytes(shiroUser.getSalt()),
                this.getName()
        );
        return info;
    }
}

shiro注解式开发

常用注解介绍

@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

我们需要在springMVC中使用shiro注解,所以需要把我们的securityManager安全管理器和我们的错误信息处理交给springMVC来管,所以就需要把它们配置进入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>

然后再Controller中运用注解

    /**
     * 用户认证注解
     * @param req
     * @param resp
     * @return
     */
    @RequiresUser
    @RequestMapping("/passUser")
    public String passUser(HttpServletRequest req,HttpServletResponse resp){
        return "admin/addUser";
    }

    /**
     * 角色认证注解
     * @param req
     * @return
     */
    @RequiresRoles(value = {"1","4"},logical = Logical.OR)
    @RequestMapping("/passRole")
    public String passRole(HttpServletRequest req,HttpServletResponse resp){
        return "admin/listUser";
    }

    /**
     * 权限认证注解
     * @param req
     * @return
     */
    @RequiresPermissions(value = {"user:update","user:view"},logical = Logical.OR)
    @RequestMapping("/passPer")
    public String passPer(HttpServletRequest req,HttpServletResponse resp){
        return "admin/resetPwd";
    }


    @RequestMapping("/unauthorized")
    public String unauthorized(HttpServletRequest req,HttpServletResponse resp){
        return "unauthorized";
    }

然后前端main页面改了跳转方法,来分别测试

    shiro注解标签
    <li>
        <r:hasPermission name="user:create">
            <a href="${pageContext.request.contextPath}/passUser">用户认证</a>
        </r:hasPermission>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/passRole">角色认证</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/passPer">权限认证</a>
    </li>

最终效果是:如果直接进入页面会进入错误处理页面,只有登录了相关权限的用户才能点击进入
end…

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
这是一个shiro的入门Demo.. 使用了Spring MVC,mybaits等技术.. 数据库设计 : User : name--password Role : id--userid--roleName Function : id--userid--url tinys普通用户只能访问index.jsp admin用户通过添加了admin的permission,所以可以访问admin.jsp role用户通过添加了role角色,所以可以访问role.jsp 这是最基本的shiro的运用..目的是让你快速了解shiro的机制.. 这个Demo体现shiro的地方主要在两个类以及shiro.xml的配置文件 CustomRealm : 处理了登录验证以及授权.. ShiroAction : 用来传递登录时的用户数据..转换为token传递给realm...之后根据结果做相应的逻辑处理.. shiro.xml : shiro的主要配置... 规则定义在以下地方 : <!-- 过滤链定义 --> <property name="filterChainDefinitions"> <value> /login.jsp* = anon /index.jsp* = authc /index.do* = authc /admin.jsp*=authc,perms[/admin] /role.jsp*=authc,roles[role] </value> </property> 2015-10-28更新 --通过添加了以下内容来使用注解配置权限.... <!-- Support Shiro Annotation 必须放在springMVC配置文件中 --> <!-- 异常处理,权限注解会抛出异常,根据异常返回相应页面 --> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="org.apache.shiro.authz.UnauthorizedException">unauth</prop> <prop key="org.apache.shiro.authz.UnauthenticatedException">login</prop> </props> </property> </bean> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor" /> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager" /> </bean> <!-- end --> --修改了过滤链 <!-- 过滤链定义 --> //简单的讲就是把需要特别处理的路径写到前面,越特殊写到越前 <property name="filterChainDefinitions"> <value> <!-- 注意这里需要把前缀写全.../shiro这里 --> /shiro/login.do*=anon /login.jsp* = anon /admin.jsp*=authc,perms[/admin] /role.jsp*=authc,roles[role] /** = authc </value> </property>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不愿秃头的阳某

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

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

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

打赏作者

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

抵扣说明:

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

余额充值