シロの最初のプログラム:公式クイックスタートプログラムクイックスタート詳細チュートリアル



1.ダウンロードして解凍します

最初のダウンロードShirohttps//github.com/apache/shiroダウンロード
画像-20201013230542649
後に解凍します
画像-20201013230605248



2.最初のシロプログラム

次に、公式文書に従って最初のシロプログラムを書きます

公式文書:

新しい通常のmavenプロジェクトを作成し、srcディレクトリを削除してから、新しいプロジェクトを作成しますmodulehello-shiro

公式文書によると:
画像-20201013231730485
次にsamples/quickstartディレクトリに入ると、srcディレクトリと対応するpom.xmlが表示されます。これは、mavenプロジェクトのソースコードをすばやく開始するためのものです。次に、プロジェクトに対応するコードを独自の作成にコピーします。プロジェクトでは
画像-20201013230913910


1.依存関係をインポートします

作成したプロジェクトのpom.xmlに依存関係をコピーpom.xmldependencyます

<dependencies>
	<dependency>
    	<groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
    </dependency>
    <!-- configure logging -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

次に、バージョン番号の依存関係に置き換えscopeます。属性の削除に注意してくださいそうしないと、テスト結果が成功しません。

<dependencies>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>1.6.0</version>
    </dependency>
    <!-- configure logging -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>2.0.0-alpha1</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>2.0.0-alpha1</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
</dependencies>

2.shiro構成ファイルを構成します

quickstart\src\main\resourceslog4j.propertiesshiro.iniプロジェクトリソースディレクトリにコピー私たちは、プラグインをインストールするために、我々はをクリックし、ファイルがハイライトされていなかった、プロンプトIDEAそれをインストールしてからクリックしてそこに強調表示されるとすぐに完了
画像-20201013232245234
.iniinstall plugins

OK
画像-20201013232455343


3. Quickstart.java

プロジェクトへquickstart\src\main\javaディレクトリQuickstart.javajavaディレクトリ

画像-20201014001721584
ホットスポットを見つけた場合は、この時点で2つのホットスポットをimport削除します。


4.テストを開始します

実行するQuickstart主な方法

いくつかのログ情報が印刷されていることがわかりました。これまでに、最初のshiroプログラムのクイックスタートが完了しました。
画像-20201017181227534



3、shiro.ini分析

2つの部分に分けることができる公式のクイックスタートINIレルム構成ファイルを分析してみましょう

  • ユーザー名と対応する役割を設定する
  • ロールの権限を設定する
#快速入门INI Realm配置

#用户及其分配的角色
[users]
#用户root 密码:secret 角色:admin
root = secret, admin
#用户guest 密码:guest 角色:guest
guest = guest, guest
#用户presidentskroob 密码:12345 角色:president
presidentskroob = 12345, president
#用户darkhelmet 密码:ludicrousspeed 角色:darklord和schwartz
darkhelmet = ludicrousspeed, darklord, schwartz
#用户lonestarr 密码:vespa 角色:goodguy和schwartz
lonestarr = vespa, goodguy, schwartz

# 具有分配权限的角色
[roles]
#admin角色具有所有权限,用通配符*表示
admin = *
#schwartz角色通过lightsaber:*获得有所有权限
schwartz = lightsaber:*
#goodguy角色通过eagle5(特定实例的ID)可以dirve(动作)Winnebago(类型)
goodguy = winnebago:drive:eagle5


4、Quickstart.javaソースコード分析

次の公式を分析しましょうQuickstart.java

1.指定されたクラスを使用してログオブジェクトを初期化します

private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);

ログオブジェクトを取得することにより、後続のログ情報を出力します

2..iniファイルを使用してSecurityManagerインスタンスを作成します

//创建带有realms,users,roles和permissions配置的Shiro SecurityManager的最简单方法是使用简单的ini配置
//我们将使用可提取.ini文件(在类路径的根目录下使用shiro.ini文件)的工厂返回一个SecurityManager实例
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();

//对于这个简单的示例快速入门,请使SecurityManager作为JVM单例访问。
//大多数应用程序都不会这样做,而在webapps会依靠其容器配置或web.xml进行使用
SecurityUtils.setSecurityManager(securityManager);

この時点で、基本的なシロ環境が設定されています。次に行うことは、私自身の操作の一部です。

3.現在実行中のユーザーサブジェクトを取得します

//获取当前执行的用户subject
Subject currentUser = SecurityUtils.getSubject();

4.現在のユーザーからセッションアクセス値を取得して印刷します

//通过当前用户得到session,使用Session做一些事情(不需要Web或EJB容器)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");//设置session其中的值
String value = (String) session.getAttribute("someKey");//获取session中值
if (value.equals("aValue")) {
    
    
    log.info("Retrieved the correct value! [" + value + "]");//通过日志打印session的值
}

5.現在のユーザーが認証されているかどうかをテストします

//测试当前用户是否被认证
if (!currentUser.isAuthenticated()) {
    
    //如果没有被认证
    UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");//生成一个Token令牌,随机设置
    token.setRememberMe(true);//设置记住我
    try {
    
    
        currentUser.login(token);//执行登录操作
    } catch (UnknownAccountException uae) {
    
    //未知的账户
        log.info("There is no user with username of " + token.getPrincipal());
    } catch (IncorrectCredentialsException ice) {
    
    //证书不正确
        log.info("Password for account " + token.getPrincipal() + " was incorrect!");
    } catch (LockedAccountException lae) {
    
    //用户被锁定
        log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                "Please contact your administrator to unlock it.");
    }
    //...还可以捕获更多异常(也许是针对您的应用程序的自定义异常)
    catch (AuthenticationException ae) {
    
    
        //意外状况?错误?
    }
}

6.現在のユーザーの主なID情報を印刷します

//打印当前用户的主要身份信息(本案例中是用户名)
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

7.現在のユーザーロールを決定します

//测试角色
if (currentUser.hasRole("schwartz")) {
    
    
    log.info("May the Schwartz be with you!");
} else {
    
    
    log.info("Hello, mere mortal.");
}

8.現在のユーザーの権限を決定します

//测试权限(不是实例级别:粗粒度)
if (currentUser.isPermitted("lightsaber:wield")) {
    
    
    log.info("You may use a lightsaber ring.  Use it wisely.");
} else {
    
    
    log.info("Sorry, lightsaber rings are for schwartz masters only.");
}

//(非常强大的)实例级别权限:细粒度
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
    
    
    log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
            "Here are the keys - have fun!");
} else {
    
    
    log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}

9.ログアウトして、システムを終了します

//注销
currentUser.logout();

//结束系统
System.exit(0);

完全な注釈付きコード:

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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


//简单的快速入门应用程序,显示了如何使用Shiro的API
public class Quickstart {
    
    

    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);


    public static void main(String[] args) {
    
    
        //创建带有realms,users,roles和permissions配置的Shiro SecurityManager的最简单方法是使用简单的ini配置
        //我们将使用可提取.ini文件(在类路径的根目录下使用shiro.ini文件)的工厂返回一个SecurityManager实例
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        //对于这个简单的示例快速入门,请使SecurityManager作为JVM单例访问。
        //大多数应用程序都不会这样做,而在webapps会依靠其容器配置或web.xml进行使用
        SecurityUtils.setSecurityManager(securityManager);

        //现在已经建立了一个简单的Shiro环境,接下来可以进行一些操作

        //获取当前执行的用户subject
        Subject currentUser = SecurityUtils.getSubject();

        //通过当前用户得到session,使用Session做一些事情(不需要Web或EJB容器)
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");//设置值
        String value = (String) session.getAttribute("someKey");//获取值
        if (value.equals("aValue")) {
    
    
            log.info("Retrieved the correct value! [" + value + "]");
        }

        //让我们登录当前用户,以便我们可以检查角色和权限
        //测试当前用户是否被认证
        if (!currentUser.isAuthenticated()) {
    
    //如果没有被认证
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");//生成一个Token令牌,随机设置
            token.setRememberMe(true);//设置记住我
            try {
    
    
                currentUser.login(token);//执行登录操作
            } catch (UnknownAccountException uae) {
    
    //未知的账户
                log.info("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
    
    //证书不正确
                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
    
    //用户被锁定
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }
            //...还可以捕获更多异常(也许是针对您的应用程序的自定义异常)
            catch (AuthenticationException ae) {
    
    
                //意外状况?错误?
            }
        }

        //打印当前用户的主要身份信息(本案例中是用户名)
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //测试角色
        if (currentUser.hasRole("schwartz")) {
    
    
            log.info("May the Schwartz be with you!");
        } else {
    
    
            log.info("Hello, mere mortal.");
        }

        //测试权限(不是实例级别:粗粒度)
        if (currentUser.isPermitted("lightsaber:wield")) {
    
    
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
    
    
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }

        //(非常强大的)实例级别权限:细粒度
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
    
    
            log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
    
    
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }

        //注销
        currentUser.logout();

        //结束系统
        System.exit(0);
    }
}

おすすめ

転載: blog.csdn.net/qq_45173404/article/details/109289607