• Hello Shiro


    【HelloWorld Shiro】

    1.搭建开发环境-加入jar包

    2.步骤(前提:已下载好Shiro资源包):

    ①找到shiro-root-1.2.3-source-release包,

    ②按Apache Shiroshiro-root-1.2.3-source-releaseshiro-root-1.2.3samplesquickstartsrcmain esources路径找到,将log4j.properties,shiro.ini文件加入到类路径(src)下,

    ③创建一个包,将Apache Shiroshiro-root-1.2.3-source-releaseshiro-root-1.2.3samplesquickstartsrcmainjava下的Quickstart.java文件放入包中。(注意:在该java代码中要添加包名代码)

    3.运行结果:一大堆东西

    附:

    Quickstart.java:

      1 package com.hk.shiro.hello;
      2 
      3 /*
      4  * Licensed to the Apache Software Foundation (ASF) under one
      5  * or more contributor license agreements.  See the NOTICE file
      6  * distributed with this work for additional information
      7  * regarding copyright ownership.  The ASF licenses this file
      8  * to you under the Apache License, Version 2.0 (the
      9  * "License"); you may not use this file except in compliance
     10  * with the License.  You may obtain a copy of the License at
     11  *
     12  *     http://www.apache.org/licenses/LICENSE-2.0
     13  *
     14  * Unless required by applicable law or agreed to in writing,
     15  * software distributed under the License is distributed on an
     16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     17  * KIND, either express or implied.  See the License for the
     18  * specific language governing permissions and limitations
     19  * under the License.
     20  */
     21 
     22 import org.apache.shiro.SecurityUtils;
     23 import org.apache.shiro.authc.*;
     24 import org.apache.shiro.config.IniSecurityManagerFactory;
     25 import org.apache.shiro.mgt.SecurityManager;
     26 import org.apache.shiro.session.Session;
     27 import org.apache.shiro.subject.Subject;
     28 import org.apache.shiro.util.Factory;
     29 import org.slf4j.Logger;
     30 import org.slf4j.LoggerFactory;
     31 
     32 
     33 /**
     34  * Simple Quickstart application showing how to use Shiro's API.
     35  * 这是一个简单地快速开始,来演示怎么用Shiro 的API。
     36  * @since 0.9 RC2
     37  */
     38 public class Quickstart {
     39 
     40     private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
     41 
     42     public static void main(String[] args) {
     43 
     44         // The easiest way to create a Shiro SecurityManager with configured
     45         // realms, users, roles and permissions is to use the simple INI config.
     46         // We'll do that by using a factory that can ingest a .ini file and
     47         // return a SecurityManager instance:
     48 
     49         // Use the shiro.ini file at the root of the classpath
     50         // (file: and url: prefixes load from files and urls respectively):
     51         Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
     52         SecurityManager securityManager = factory.getInstance();
     53 
     54         // for this simple example quickstart, make the SecurityManager
     55         // accessible as a JVM singleton.  Most applications wouldn't do this
     56         // and instead rely on their container configuration or web.xml for
     57         // webapps.  That is outside the scope of this simple quickstart, so
     58         // we'll just do the bare minimum so you can continue to get a feel
     59         // for things.
     60         SecurityUtils.setSecurityManager(securityManager);
     61 
     62         // Now that a simple Shiro environment is set up, let's see what you can do:
     63 
     64         // get the currently executing user:
     65         //获取当前的subject,调用SecurityUtils.getSubject()
     66         Subject currentUser = SecurityUtils.getSubject();
     67 
     68         // Do some stuff with a Session (no need for a web or EJB container!!!)
     69         //测试使用session
     70         //获取Session,调用subject的getSession()方法
     71         Session session = currentUser.getSession();
     72         session.setAttribute("someKey", "aValue");
     73         String value = (String) session.getAttribute("someKey");
     74         if (value.equals("aValue")) {
     75             log.info("Retrieved the correct value! [" + value + "]");
     76         }
     77 
     78         // let's login the current user so we can check against roles and permissions:
     79         //测试当前的用户是否已经被认证,即是否登录
     80         //调用subject的isAuthenticated()
     81         if (!currentUser.isAuthenticated()) {
     82             //把用户名和密码封装成UsernamePasswordToken对象
     83             UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
     84             //rememberme
     85             token.setRememberMe(true);
     86             try {
     87                 //执行登录
     88                 currentUser.login(token);
     89                 //若没有指定账户,Shiro则抛出UnknownAccountException异常
     90             } catch (UnknownAccountException uae) {
     91                 log.info("There is no user with username of " + token.getPrincipal());
     92                 //若账户存在,密码不匹配,则Shiro抛出IncorrectCredentialsException
     93             } catch (IncorrectCredentialsException ice) {
     94                 log.info("Password for account " + token.getPrincipal() + " was incorrect!");
     95                 //用户被锁定的异常
     96             } catch (LockedAccountException lae) {
     97                 log.info("The account for username " + token.getPrincipal() + " is locked.  " +
     98                         "Please contact your administrator to unlock it.");
     99             }
    100             // ... catch more exceptions here (maybe custom ones specific to your application?
    101             //所有认证时异常的父类
    102             catch (AuthenticationException ae) {
    103                 //unexpected condition?  error?
    104             }
    105         }
    106 
    107         //say who they are:
    108         //print their identifying principal (in this case, a username):
    109         log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
    110 
    111         //test a role:
    112         //测试是否有某一个角色,调用subject的hasRole方法
    113         if (currentUser.hasRole("schwartz")) {
    114             log.info("May the Schwartz be with you!");
    115         } else {
    116             log.info("Hello, mere mortal.");
    117         }
    118 
    119         //test a typed permission (not instance-level)
    120         //测试用户是否具备某一个行为
    121         if (currentUser.isPermitted("lightsaber:weild")) {
    122             log.info("You may use a lightsaber ring.  Use it wisely.");
    123         } else {
    124             log.info("Sorry, lightsaber rings are for schwartz masters only.");
    125         }
    126 
    127         //a (very powerful) Instance Level permission:
    128         if (currentUser.isPermitted("winnebago:drive:eagle5")) {
    129             log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
    130                     "Here are the keys - have fun!");
    131         } else {
    132             log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    133         }
    134 
    135         //all done - log out!
    136         //执行登出,调用subject的logout()方法
    137         currentUser.logout();
    138 
    139         System.exit(0);
    140     }
    141 }
    每接触一个新领域,我就像一块掉进水里的海绵,四面八方的养分都让我不断充实。O(∩_∩)O~
  • 相关阅读:
    Netty的常用概念
    netty学习
    MarkDown思考
    Xshell配置SSH秘钥登录
    Maven中避开测试环节
    Maven文件配置
    机器学习资源
    数学问题-高精度运算
    对局匹配
    发现环
  • 原文地址:https://www.cnblogs.com/zhzcode/p/9673522.html
Copyright © 2020-2023  润新知