Shiro环境配置

Shiro 简介:

Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。

使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。

Shiro 主要功能:

三个核心组件:Subject, SecurityManager 和 Realms.

Subject:即“当前操作用户”。但是,在Shiro中,Subject这一概念并不仅仅指人,也可以是第三方进程、后台帐户(Daemon Account)或其他类似事物。它仅仅意味着“当前跟软件交互的东西”。
Subject代表了当前用户的安全操作!

SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通过SecurityManager来管理内部组件实例,并通过它来提供安全管理的各种服务。
SecurityManager则管理所有用户的安全操作!

Realm: Realm充当了Shiro与应用安全数据间的“桥梁”或者“连接器”。也就是说,当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。

导入依赖:
<dependencies>
        <!--核心shiro依赖-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.1</version>
        </dependency>
        <!--日志门面-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.36</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
在resource下创建log4j.properties
log4j.rootLogger=INFo,appender 
log4j.appender.appender=org.apache.log4j.ConsoleAppender  
log4j.appender.appender.layout=org.apache.log4j.TTCCLayout

log4j.appender.stdout=org.apache.log4j.consoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n

#General Apache libraries
log4j.logger.org.apache=WARN

#Spring
log4j.logger.org.springframework=WARN

#Default Shiro Logging
log4j.logger.org.apache.shiro=INFO

#Disable verbose Logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

在resource下创建shiro.ini
[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

配置ini,若不显示高亮,可添加如下插件!

在这里插入图片描述

创建Quickstart类:(这个很重要,要反复多看!)
package com.jin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Simple Quickstart application showing how to use Shiro's API.
 *
 * @since 0.9 RC2
 */
public class Quickstart {

    //日志(框架)输出
    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);


    public static void main(String[] args) {

        // The easiest way to create a Shiro SecurityManager with configured
        // realms, users, roles and permissions is to use the simple INI config.
        // We'll do that by using a factory that can ingest a .ini file and
        // return a SecurityManager instance:
        /**
         * // 创建 Shiro 安全管理器 的最简单方法
         * // 领域、用户、角色和权限是使用简单的 INI 配置。
         * // 我们将通过使用一个可以摄取 .ini 文件的工厂来做到这一点
         * // 返回一个 SecurityManager(安全管理器) 实例:
         */
        // Use the shiro.ini file at the root of the classpath
        // (file: and url: prefixes load from files and urls respectively):
        /**
         * // 使用类路径根目录下的 shiro.ini 文件
         * // (file: 和 url: 前缀分别从文件和 url 加载):
         */

        DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
        IniRealm iniRealm=new IniRealm("classpath:shiro.ini");
        defaultSecurityManager.setRealm(iniRealm);

        // for this simple example quickstart, make the SecurityManager
        // accessible as a JVM singleton.  Most applications wouldn't do this
        // and instead rely on their container configuration or web.xml for
        // webapps.  That is outside the scope of this simple quickstart, so
        // we'll just do the bare minimum so you can continue to get a feel
        // for things.
        /**
         * // 对于这个简单的示例快速入门,创建 SecurityManager
         * // 可作为 JVM 单例访问。 大多数应用程序不会这样做
         * // 而是依赖他们的容器配置或 web.xml
         * // 网络应用程序。 这超出了这个简单快速入门的范围,所以
         * // 我们只做最低限度的工作,这样您就可以继续感受事物。
         */
        SecurityUtils.setSecurityManager(defaultSecurityManager);

        // Now that a simple Shiro environment is set up, let's see what you can do:

        /**
         * // 现在一个简单的 Shiro 环境已经搭建好了,让我们看看你能做什么:
         */
        // get the currently executing user:
        /**
         * // 获取当前正在执行的用户:
         */

        // 获取当前的用户对象 Subject
        Subject currentUser = SecurityUtils.getSubject();

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        /**
         * // 使用 Session 做一些事情(不需要 Web 或 EJB 容器!!!)
         */

        //通过当前用户拿到Session
        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 + "]");
        }

        // let's login the current user so we can check against roles and permissions:
        /**
         * // 让我们登录当前用户,以便我们检查角色和权限:
         */

        //判断当前用户是否被认证~
        if (!currentUser.isAuthenticated()) {
            //Token : 令牌 ! 没有获取 ,随机
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            //设置记住我
            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 more exceptions here (maybe custom ones specific to your application?
            /**
             * // ...在此处捕获更多异常(可能是特定于您的应用程序的自定义异常?
             */
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
                /**
                 * //意外情况? 错误?
                 */
            }
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
        /**
         * //说出他们是谁:
         * //打印他们的识别主体(在本例中为用户名):
         */
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

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

        //test a typed permission (not instance-level)
        /**
         * //测试一个类型化的权限(不是实例级别的)
         */

        //粗粒度
        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.");
        }

        //a (very powerful) Instance Level permission:
        /**
         * //一个(非常强大的)实例级权限:
         */
        
        //细粒度
        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!");
        }

        //all done - log out!
        /**
         * //全部完成 - 退出!
         */
        currentUser.logout();

        //结束系统!
        System.exit(0);
    }
}
显示效果如下:

在这里插入图片描述

恭喜你,完成了Shiro环境配置!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要配置Shiro环境,需要完成以下步骤: 1. 添加Shiro依赖:在项目的pom.xml文件中添加Shiro依赖项,例如: ```xml <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.7.1</version> </dependency> ``` 2. 配置Shiro:创建一个shiro.ini文件(或者shiro.properties文件),并配置Shiro security manager和相应的realm,例如: ```ini [main] # 定义一个JDBC realm jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm jdbcRealm.authenticationQuery = SELECT password FROM users WHERE username = ? jdbcRealm.userRolesQuery = SELECT role_name FROM user_roles WHERE username = ? # 定义一个security manager,使用上述的JDBC realm securityManager.realms = $jdbcRealm ``` 3. 在应用程序中使用Shiro:在需要进行安全认证的地方调用Shiro API,例如: ```java // 创建一个SecurityManager实例 SecurityManager securityManager = new IniSecurityManagerFactory("classpath:shiro.ini").getInstance(); // 将SecurityManager绑定到当前线程 SecurityUtils.setSecurityManager(securityManager); // 获取Subject对象 Subject currentUser = SecurityUtils.getSubject(); // 认证当前用户 UsernamePasswordToken token = new UsernamePasswordToken("username", "password"); currentUser.login(token); // 检查用户是否被授权 if (currentUser.hasRole("admin")) { // 执行管理员操作 } else { // 执行普通用户操作 } ``` 以上是Shiro的基本配置和使用方法,根据具体的应用场景和需求,可能还需要进行一些额外的配置和定制。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

已转行@

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

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

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

打赏作者

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

抵扣说明:

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

余额充值