Shiro入门教程

简介: 简介Shiro是一个强大的简单易用的Java安全框架,主要用来更便捷的认证,授权,加密,会话管理。Shiro首要的和最重要的目标就是容易使用并且容易理解。

简介

Shiro是一个强大的简单易用的Java安全框架,主要用来更便捷的认证,授权,加密,会话管理。Shiro首要的和最重要的目标就是容易使用并且容易理解。

Shiro是一个有许多特性的全面的安全框架,下面这幅图可以了解Shiro的特性:

img_5c8ca0a7af48f02a82a4eade97885ea5.png
image.png

可以看出shiro除了基本的认证,授权,会话管理,加密之外,还有许多额外的特性。

Shiro架构

从大的角度来看,Shiro有三个主要的概念:SubjectSecurityManagerRealms,下面这幅图可以看到这些原件之间的交互。

img_c8a4cf67e62be07941d46e943ca9620a.png
image.png
  • Subject:翻译为主角,当前参与应用安全部分的主角。可以是用户,可以试第三方服务,可以是cron 任务,或者任何东西。主要指一个正在与当前软件交互的东西。
    所有Subject都需要SecurityManager,当你与Subject进行交互,这些交互行为实际上被转换为与SecurityManager的交互

  • SecurityManager:安全管理员,Shiro架构的核心,它就像Shiro内部所有原件的保护伞。然而一旦配置了SecurityManager,SecurityManager就用到的比较少,开发者大部分时间都花在Subject上面。
    请记得,当你与Subject进行交互的时候,实际上是SecurityManager在背后帮你举起Subject来做一些安全操作。

  • Realms:Realms作为Shiro和你的应用的连接桥,当需要与安全数据交互的时候,像用户账户,或者访问控制,Shiro就从一个或多个Realms中查找。
    Shiro提供了一些可以直接使用的Realms,如果默认的Realms不能满足你的需求,你也可以定制自己的Realms

更细节的架构

img_b6fb6291d986929dfb3e9cf573dbba49.png
image.png

创建Shiro应用

使用Idea创建一个Maven项目

Pom.xml中添加如下依赖:

 <dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.2.3</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.1</version>
        </dependency>
    </dependencies>

任意创建一个包,在里面创建一个Tutorial类

package me.aihe;import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

public class Tutorial {
    private static final transient Logger log = LoggerFactory.getLogger(Tutorial.class);   

    public static void main(String[] args) {    
        log.info("My First Apache Shiro Application");       
        System.exit(0);    
    }
}

使用Shiro

Shiro提供了一个通用的方案通过 INI 进行配置 ,当然也可以通过XML,YMAL,JSON等进行配置。
在resource目录下面,创建一个shiro.ini的文件。内容如下:

# -----------------------------------------------------------------------------
# Users and their (optional) assigned roles
# username = password, role1, role2, ..., roleN
# -----------------------------------------------------------------------------
[users]
root = secret, admin
guest = guest, guest
presidentskroob = 12345, president
darkhelmet = ludicrousspeed, darklord, schwartz
aihe = aihe, goodguy, client

# -----------------------------------------------------------------------------
# Roles with assigned permissions
# roleName = perm1, perm2, ..., permN
# -----------------------------------------------------------------------------
[roles]
admin = *
client = look:*
goodguy = winnebago:drive:eagle5

引用Shiro.ini配置进行测试

现在改变我们的Tutorial类文件,内容如下

package me.aihe;

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;

/**
 * Created by aihe on 2017/6/14.
 */
public class Tutorial {

    private static final transient Logger log = LoggerFactory.getLogger(Tutorial.class);
    public static void main(String[] args) {
        log.info("My First Apache Shiro Application");

        //1. 这里的SecurityManager是org.apache.shiro.mgt.SecurityManager,而不是java.lang.SecurityManager
        // 加载配置文件
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        //2.解析配置文件,并且返回一些SecurityManger实例
        SecurityManager securityManager = factory.getInstance();

        //3.设置SecurityManager到静态内存区,单例模式
        SecurityUtils.setSecurityManager(securityManager);


        // 安全操作
        Subject currentUser = SecurityUtils.getSubject();

        // 在应用的当前会话中设置属性
        Session session =  currentUser.getSession();
        session.setAttribute("key","value");

        //当前我们的用户是匿名的用户,我们尝试进行登录,
        if (!currentUser.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken("aihe", "aihe");

            //this is all you have to do to support 'remember me' (no config - built in!):
            token.setRememberMe(true);

            //尝试进行登录用户,如果登录失败了,我们进行一些处理

            try{
                currentUser.login(token);

                //当我们获登录用户之后
                log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");


                // 查看用户是否有指定的角色
                if ( currentUser.hasRole( "client" ) ) {
                    log.info("Look is in your role" );
                } else {
                    log.info( "....." );
                }

                // 查看用户是否有某个权限
                if ( currentUser.isPermitted( "look:desk" ) ) {
                    log.info("You can look.  Use it wisely.");
                } else {
                    log.info("Sorry, you can't look.");
                }

                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();

            }
            catch ( UnknownAccountException uae ) {
                //账户不存在的操作
            } catch ( IncorrectCredentialsException ice ) {
                //密码不正确
            } catch ( LockedAccountException lae ) {
                //用户被锁定了
            } catch ( AuthenticationException ae ) {
                //无法判断的情形
            }

        }


        System.exit(0);
    }
}

总结

这个相对来说是一个简单的程序,但也证明了一些shiro的基本用法,我们可以通过shiro进行认证,权限控制等。想要了解更多shiro的用法,请参考Shiro的官方文档

资料

目录
相关文章
|
7月前
|
Java Maven
Shiro学习-快速入门(二)
Shiro学习-快速入门(二)
35 0
|
9月前
|
缓存 数据库 数据安全/隐私保护
【Shiro】第三章 Shiro入门(四)
【Shiro】第三章 Shiro入门(四)
55 0
|
9月前
|
存储 算法 数据安全/隐私保护
【Shiro】第三章 Shiro入门(三)
【Shiro】第三章 Shiro入门(三)
60 1
|
9月前
|
安全 数据安全/隐私保护
【Shiro】第三章 Shiro入门(一)
【Shiro】第三章 Shiro入门
53 1
|
9月前
|
存储 算法 程序员
【Shiro】第三章 Shiro入门(二)
【Shiro】第三章 Shiro入门(二)
56 1
|
9月前
|
存储 缓存 安全
Shiro学习之Shiro简介
Shiro学习之Shiro简介
71 0
|
9月前
|
Java API 数据库
Shiro学习之Shiro基本使用(1)
Shiro学习之Shiro基本使用(1)
63 0
|
9月前
|
Java 数据库 数据安全/隐私保护
Shiro学习之Shiro基本使用(2)
Shiro学习之Shiro基本使用(2)
39 0
|
存储 数据采集 缓存
Shiro简介
.什么是Shiro - .ApacheShiro 是一个Java的安全(权限)框架。 - .Shiro可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境。 - .Shiro可以完成,认证,授权,加密,会话管理,Web集成,缓存等。
Shiro简介
|
存储 缓存 安全
shiro实战教程(一)
shiro实战教程(一)
126 0
shiro实战教程(一)