1、shiro Hello

一、程序架构

pom.xml:

<dependency>

  <groupId>org.apache.shiro</groupId>

  <artifactId>shiro-core</artifactId>

  <version>1.3.2</version>

</dependency>

<dependency>

  <groupId>org.apache.shiro</groupId>

  <artifactId>shiro-ehcache</artifactId>

  <version>1.3.2</version>

</dependency>

二、简单说明Shiro.ini配置文件

  2.1 内容

 [users]

root = secret, admin

guest = guest, guest

presidentskroob = 12345, president

darkhelmet = ludicrousspeed, darklord, schwartz

lonestarr = vespa, goodguy, schwartz

 

[roles]

admin = *

schwartz = lightsaber:*

goodguy = winnebago:drive:eagle5

 

2.2 ini 文件说明

[users]:用户名=密码,角色1,角色2

[roles]:角色=权限1,权限2

权限:

(1)用简单的字符串来表示一个权限。如:user

(2)多层次管理:如:user:query,user:edit,user:query,edit。第一部分为操作的领域,第二部分为执行的操作。可以使用通配符:user:*,*:query

(3)实例级权限:域:操作:实例

如:user:edit:manager 只能对 user 中的 manager 进行 edit。

通配符:user:edit:*、user:*:*、user:*:manager

等价:user:edit==user:edit:*、user == user:*:* 只能从字符串结尾处省略。

 

三、Quickstart.java

 packagecn.com.bochy.shiro;

import org.apache.shiro.SecurityUtils;

import org.apache.shiro.authc.*;

import org.apache.shiro.config.IniSecurityManagerFactory;

import org.apache.shiro.mgt.SecurityManager;

import org.apache.shiro.session.Session;

import org.apache.shiro.subject.Subject;

import org.apache.shiro.util.Factory;

public class Quickstart {

    public static void main(String[]args) {

        Factory<SecurityManager> factory= new IniSecurityManagerFactory("classpath:shiro.ini");

        SecurityManager securityManager =factory.getInstance();

        SecurityUtils.setSecurityManager(securityManager);

        Subject currentUser = SecurityUtils.getSubject();

        //用会话做一些事情

        Session session = currentUser.getSession();

        session.setAttribute("czf","123456");

        String value = (String)session.getAttribute("czf");

        //Retrieved:取回

        if (value.equals("123456")) {

           System.out.println("-->Retrieved the correct value! [" + value +"]");

        }

        // let's login the current user so we can check against roles andpermissions:

      //  System.out.println(currentUser.);

         if(!currentUser.isAuthenticated()) {//authentication:认证,身份

            UsernamePasswordToken token = newUsernamePasswordToken("lonestarr","vespa");

            token.setRememberMe(true);

            try {

                currentUser.login(token);

                System.out.println("-->User [" + currentUser.getPrincipal() +"] loggedin successfully.");

            } catch(UnknownAccountException uae) {

                //Principal:主要的,首长,负责人

                System.out.println("-->There is no user with username of " + token.getPrincipal());

            } catch (IncorrectCredentialsExceptionice) {

                System.out.println("-->Password for account " + token.getPrincipal() +" was incorrect!");

            } catch (LockedAccountExceptionlae) {

                System.out.println("The account for username " + token.getPrincipal() +" is locked.  " +

                        "Please contact your administrator to unlockit.");

            }

            // ... catch more exceptions here (maybe custom ones specific to yourapplication?

            catch (AuthenticationExceptionae) {

                //unexpected condition?  error?

            }

        }

        //test a role:

        if (currentUser.hasRole("schwartz")) {

            System.out.println("-->May the Schwartz be with you!");

        } else {

            System.out.println("Hello, mere mortal.");

        }

        //test a typed permission (not instance-level)

        //lightsaber: 激光剑;weild:行使

        if (currentUser.isPermitted("lightsaber:weild")) {

            System.out.println("-->You may use a lightsaber ring.  Use it wisely.");

        } else {

            //schwartz:施瓦兹

            System.out.println("Sorry, lightsaber rings are for schwartz mastersonly.");

        }

        //a (very powerful) Instance Level permission:

        //winnebago:温尼贝戈人;房车 eagle:鹰plate:盘子

        if (currentUser.isPermitted("winnebago:drive:eagle5")) {

            System.out.println("-->You are permitted to 'drive' the winnebagowith license plate (id) 'eagle5'.  " +

                    "Here are the keys - have fun!");

        } else {

            System.out.println("Sorry, you aren't allowed to drive the 'eagle5'winnebago!");

        }

        //all done - log out!

        currentUser.logout();

        System.exit(0);

    }

}

四、执行结果

 -->Retrieved the correct value! [123456]

-->User [lonestarr] logged in successfully.

-->May the Schwartz be with you!

-->You may use a lightsaber ring.  Use it wisely.

-->You are permitted to 'drive' the winnebago withlicense plate (id) 'eagle5'.  Here arethe keys - have fun!

 五、总结

shiro
1、shiro是一个开源免费的Java安全框架,既可以使用在java的程序上,也可以使用在java web,还可以使用在移动端。
2、两大内容
   1、身份验证
   2、授权
3、使用shiro的依赖
 <dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-core</artifactId>
  <version>1.3.2</version>
</dependency>
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-ehcache</artifactId>
  <version>1.3.2</version>
</dependency>
4、使用shiro的一般步骤
 1、读取配置文件,获取安全管理者的工厂
       Factory<SecurityManager>   factory= new IniSecurityManagerFactory("classpath:shiro.ini");
     2、获取安全管理者实例  
       SecurityManager securityManager=factory.getInstance();    
          3、设置SecurityUtils的SecurityManager
       SecurityUtils.setSecurityManager(securityManager);
           4、获取当前Subject对象(user) 
     Subject currrentUser=  SecurityUtils.getSubject();
     5、身份验证
      UsernamePasswordToken token=new UsernamePasswordToken(用户名,密码);
         currrentUser.login(token);
     6、授权验证
     7、注销用户
  5、shiro如何判断某个用户拥有哪个角色?
       currrentUser.hasRole(角色名)
       currrentUser.hasAllRoles(多个角色)
  6、如何判断某个用户是否可以访问某个资源
      currentUser.isPermitted(资源名)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值