shiro学习笔记十二:shiro权限注解

一、项目说明

项目环境:jdk1.7+tomcat7+idea2018+maven+shiro1.3.2

源代码github地址:https://github.com/tmAlj/shiro/tree/master/ssms

实现目标:通过使用部分权限注解,实现相应的效果,达到对shiro的权限注解的使用与理解

综合实例:基于shiro的按钮级别的权限管理系统

二、权限注解

        注:shiro提供了相应的注解用于权限控制,如果使用这些注解就需要使用aop的功能来进行判断。shiro提供了spring aop集成,用于权限注解的解析和验证

(1)@RequiresAuthentication :表示当前Subject已经通过login 进行了身份验证;即Subject. isAuthenticated()返回true

(2)@RequiresUse:表示当前Subject已经身份验证或者通过记住我登录的

(3)@RequiresGuest :表示当前Subject没有身份验证或通过记住我登录过,即是游客身份

(4)@RequiresRoles(value={“admin”, “user”}, logical= Logical.AND)

(5)@RequiresPermissions (value={“user:a”, “user:b”}, logical= Logical.OR) :表示当前Subject需要权限user:a或user:b

三、使用示例

        注:注解可以用在service或controller中,本节所有示例基于shiro学习笔记十一:shiro中的jsp标签

(1)配置aop注解

        注:在spring-shiro-config.xml配置

<!-- 配置shiro中bean生命周期管理器 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!-- AOP式方法级权限检查 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
	  depends-on="lifecycleBeanPostProcessor">
	<property name="proxyTargetClass" value="true" />
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
	<property name="securityManager" ref="securityManager"/>
</bean>

(2)开启注解

        注:需要在spring-mvc-config.xml配置aop注解的启动,如果在spring或shiro配置中配置,可能后面使用注解的时候无效

<!-- 开启shiro中aop注解 -->
<aop:config proxy-target-class="true"></aop:config>

(3)配置controller

    //注入service
    @Autowired
    ShiroServiceImpl ssi;

    /**
     * 权限注解测试
     * @return
     */
    @RequestMapping("/test")
    public String note(){
        ssi.test();
        return "redirect:/welcom.jsp";
    }

(4)配置service

package com.wsd.service.impl;

import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Service;

/**
 * Created by tm on 2018/8/19.
 * 权限注解测试service
 */
@Service("ShiroServiceImpl")
public class ShiroServiceImpl {

    //只有admin角色才能访问该方法,其他角色访问将会抛出异常
    @RequiresRoles({"admin"})
    public void test(){
        System.out.println("xxxxxxxxxxxxxxxxxxxx");
    }
}

(5)welcom.jsp页面添加测试链接

74d8a7c437c0a6ac778ae08ccae29f4117a.jpg

四、测试示例

        注:示例是通过在service方法上使用@RequiresRoles({"admin"})注解,当用户为admin/123456时,会调用该方法;当用户为user/123456时在调用该方法时会抛出异常

(1)登录/login.jsp

7cacb4ba4c4cc4a66d007d0b4b36f6ce3aa.jpg

(2)登录成功/welcom.jsp

1e203e67578ddccfd7b054d23c068e15ecd.jpg

(3)非admin用户登录

611934f66d52bb64981beabb66ed2e35cfc.jpg

(4)admin用户登录

cd77e389a45802cddee43b6d432127c9ae9.jpg

转载于:https://my.oschina.net/tij/blog/1930267

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值