Shiro学习--Apache Shiro Tutorial 环境搭建

1 Shiro介绍

Apache Shiro介绍

参考

http://shiro.apache.org/introduction.html

这里写图片描述

Shiro 包括

  • Authentication: Sometimes referred to as ‘login’, this is the act of
    proving a user is who they say they are.

  • Authorization: The process of access control, i.e. determining ‘who’
    has access to ‘what’.

  • Session Management: Managing user-specific sessions, even in non-web
    or EJB applications.

  • Cryptography: Keeping data secure using cryptographic algorithms
    while still being easy to use.

第一个是认证,第二个是授权,第三个会话管理,第四个是加密。

2 Apache Shiro Tutorial 环境搭建

Apache Shiro Tutorial

参考

http://shiro.apache.org/tutorial.html

pom依赖

    <dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.5</version>
        </dependency>
    </dependencies>

The first thing to understand in enabling Shiro in an application is that almost everything in Shiro is related to a central/core component called the SecurityManager. For those familiar with Java security, this is Shiro’s notion of a SecurityManager - it is NOT the same thing as the java.lang.SecurityManager.

Shiro SecurityManager is the core of a Shiro environment for an application and one SecurityManager must exist per application. So, the first thing we must do in our Tutorial application is set-up the SecurityManager instance.

Shiro的核心就是SecurityManager。
所以第一件事情就是使用 SecurityManager

Shiro provides a default ‘common denominator’ solution via text-based INI configuration. People are pretty tired of using bulky XML files these days, and INI is easy to read, simple to use, and requires very few dependencies. You’ll also see later that with a simple understanding of object graph navigation, INI can be used effectively to configure simple object graphs like the SecurityManager.

Shiro提供了一个默认的基于文本的INI配置。

创建ini文件

src/main/resources/shiro.ini

# =============================================================================
# Tutorial INI configuration
#
# Usernames/passwords are based on the classic Mel Brooks' film "Spaceballs" :)
# =============================================================================

# -----------------------------------------------------------------------------
# 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
lonestarr = vespa, goodguy, schwartz

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

测试

package com.shiro.test;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by GWCheng on 2016/3/6.
 */
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.
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        //2.
        SecurityManager securityManager = factory.getInstance();

        //3.
        SecurityUtils.setSecurityManager(securityManager);

        System.exit(0);
    }
}

项目结构

这里写图片描述

到这里虽然并没有任何输出,可是Shiro的环境确实已经搭建完成。

3 更进一步

Now that our SecurityManager is set-up and ready-to go, now we can start doing the things we really care about - performing security operations.

让我们更进一步

When securing our applications, probably the most relevant questions we ask ourselves are “Who is the current user” or “Is the current user allowed to do X” It is common to ask these questions as we’re writing code or designing user interfaces: applications are usually built based on user stories, and you want functionality represented (and secured) based on a per-user basis. So, the most natural way for us to think about security in our application is based on the current user. Shiro’s API fundamentally represents the notion of ‘the current user’ with its Subject concept.

当我们确保我们的系统安全的时候,我们经常会问:当前用户是谁?他有做xxx的权限吗?最常见的思考方式就是通过当前用户来考虑系统的安全性。Shiro的API是通过Subject来描述当前用户的。

通过以下代码得到当前用户

Subject currentUser = SecurityUtils.getSubject();

Using SecurityUtils.getSubject(), we can obtain the currently executing Subject. Subject is a security term that basically means “a security-specific view of the currently executing user”. It is not called a ‘User’ because the word ‘User’ is usually associated with a human being. In the security world, the term ‘Subject’ can mean a human being, but also a 3rd party process, cron job, daemon account, or anything similar. It simply means ‘the thing that is currently interacting with the software’. For most intents and purposes though, you can think of the Subject as Shiro’s ‘User’ concept.

通过SecurityUtils.getSubject()我们就可以获得当前正在执行的用户,用户通常是指正在与软件交互的。可以将Subject理解为Shiro的用户。

Now that you have a Subject, what can you do with it

If you want to make things available to the user during their current session with the application, you can get their session:

Session session = currentUser.getSession();
session.setAttribute( "someKey", "aValue" );

官方的解释还是有点太繁琐,我们直接上代码

完整的测试代码

Tutorial.java

package com.shiro.test;

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

/**
 * Created by GWCheng on 2016/3/6.
 */
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工厂,此处使用Ini配置文件初始化SecurityManager 
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        //2、得到SecurityManager实例 并绑定给SecurityUtils
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        // 得到当前用户 get the currently executing user:
        Subject currentUser = SecurityUtils.getSubject();

        // 不需要web容器,也可以Do some stuff with a Session (no need for a web or EJB container!!!)
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        // 拿到刚才设置的session
        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()) {
            // lonestarr是 shior.ini中的用户,vespa是lonestarr的密码
            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)
        // 测试用户的权限,因为lonestarr在schwartz组中
        // schwartz = lightsaber:*  schwartz组有权限
        if (currentUser.isPermitted("lightsaber:weild")) {
            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.ini的解释如下,再配上注释,应该很清晰了!

这里写图片描述

总结

这篇文章主要讲了如何配置并启动Shiro,别介绍了Shiro的两个核心概念SecurityManager和Subject。

后序会介绍不用其他特性。

ok,Shiro环境搭建就到这里!

参考文献

http://shiro.apache.org/tutorial.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值