Shiro 系列: 简单命令行程序示例

在本示例中, 使用 INI 文件来定义用户和角色. 首先学习一下 INI 文件的规范. 

 

=======================
Shiro INI 的基本规范
=======================
[main]
# 在这里定义 SecurityManager 和 Realms 等

[users]
# 每一行定义一个用户, 格式是 username = password, role1, role2, ..., roleN

[roles]
# 角色在这里定义, 格式是 roleName = perm1, perm2, ..., permN
# 说明1: 权限名可以使用带有层次的命名方式, 使用冒号来分割层次关系, 比如 user:create 或 user:poweruser:update 权限.
# 说明2: user:* 这样的权限, 代表具有 user:create 和 user:poweruser:update 权限.

[urls]
# 对于web系统, 可在这里定义url的权限配置.

 

==========================
pom
==========================
Shiro jar需要 slf4j 依赖项.

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.4.0</version>
    <exclusions>
        <exclusion>
            <artifactId>slf4j-api</artifactId>
            <groupId>org.slf4j</groupId>
        </exclusion>
    </exclusions>
</dependency>


# =======================
shiro.ini 示例文件的内容
# =======================

# =======================
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

 

==========================
API 代码示例
==========================

@Override
public void run(String... args) throws Exception {
    // 创建sessionFactory,使用ini配置文件初始化
    IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    // 创建securityManager实例
    SecurityManager securityManager = factory.getInstance();

    // 将securityManager配置在当前运行环境中
    SecurityUtils.setSecurityManager(securityManager);

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

    // session 操作
    Session session = currentUser.getSession();
    System.out.println("Id:" + session.getId());

    session.setAttribute("name", "value");
    System.out.println(session.getAttribute("name"));

    if (!currentUser.isAuthenticated()) {
        // 登录需要一个 token
        UsernamePasswordToken token = new UsernamePasswordToken("root", "secret");

        // 在 token 上设置 RememberMe
        // token.setRememberMe(true);

        // 登录
        currentUser.login(token);

        // 登录后可获取认证身份(一个或多个)
        PrincipalCollection principals = currentUser.getPrincipals();
        for (Object principal : principals) {
            System.out.println(principal.toString());
        }

        // 角色检查
        boolean granted1 = currentUser.hasRole("admin");
        System.out.println("hasRole('admin'):" + granted1);

        boolean granted2 = currentUser.hasRole("winnebago:drive");
        System.out.println("hasRole('winnebago:drive'):" + granted1);

        // 角色检查断言, 如果没有对应的角色, 会抛出 AuthorizationExceptions
        currentUser.checkRole("admin");

        // 权限检查
        boolean granted3 = currentUser.isPermitted("winnebago:drive");
        System.out.println("isPermitted('winnebago:drive'):" + granted2);

        // 权限检查断言, 如果没有对应的权限, 会抛出 AuthorizationExceptions
        currentUser.checkPermission("winnebago:drive");

        // 登出
        currentUser.logout();

    } else {
        System.out.println("you have login");
    }
}

结果输出为:

Id:71b126e5-a79c-416d-9abb-1b5430eaf5c3
value
root
hasRole('admin'):true
hasRole('winnebago:drive'):true
isPermitted('winnebago:drive'):false


==========================
参考
==========================
https://www.jianshu.com/p/5a35d0100a71

 

posted @ 2018-11-18 16:48  harrychinese  阅读(743)  评论(0编辑  收藏  举报