Shiro快速入门

Shiro快速入门

    • 1、前言
      • 1.1 什么是Shiro
      • 1.2 shiro有哪些功能
      • 1.3 shiro架构
    • 2、快速入门

1、前言

1.1 什么是Shiro

  1. shiro是apache的一个开源框架,是一个权限管理的框架,实现 用户认证、用户授权。
  2. spring中有springsecurity (原名Acegi),是一个权限框架,它和spring依赖过于紧密,没有shiro使用简单。
  3. shiro不依赖于spring,shiro不仅可以实现 web应用的权限管理,还可以实现c/s系统。
  4. 分布式系统权限管理,shiro属于轻量框架,越来越多企业项目开始使用shiro。

1.2 shiro有哪些功能

  1. Authentication:身份认证、登录,验证用户是不是拥有相应的身份;
  2. Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限,即判断用户能否 进行什么操作,如:验证某个用户是否拥有某个角色,或者细粒度的验证某个用户对某个资源是否 具有某个权限!
  3. Session Manager:会话管理,即用户登录后就是第一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通的JavaSE环境,也可以是Web环境;
  4. Cryptography:加密,保护数据的安全性,如密码加密存储到数据库中,而不是明文存储;
  5. WebSupport:Web支持,可以非常容易的集成到Web环境;
  6. Caching:缓存,比如用户登录后,其用户信息,拥有的角色、权限不必每次去查,这样可以提高 效率
  7. Concurrency:Shiro支持多线程应用的并发验证,即,如在一个线程中开启另一个线程,能把权限 自动的传播过去
  8. Testing:提供测试支持; Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问;
  9. Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了

1.3 shiro架构

Shiro快速入门_第1张图片

  • subject(*):主体,可以是用户也可以是程序,主体要访问系统,系统需要对主体进行认证、授权。
  • securityManager(*):安全管理器,主体进行认证和授权都是通过securityManager进行。securityManager是一个集合,真正做事的不是securityManager而是它里面的东西。
  • authenticator():认证器,主体进行认证最终通过authenticator进行的。注:用于账号密码
    authorizer():授权器,主体进行授权最终通过authorizer进行的。
  • sessionManager():web应用中一般是用web容器(中间件tomcat)对session进行管理,shiro也提供一套session管理的方式。shiro不仅仅可以用于web管理也可以用于cs管理,所以他不用web容器的session管理。
  • SessionDao: 通过SessionDao管理session数据,针对个性化的session数据存储需要使用sessionDao
  • cache Manager:缓存管理器,主要对session和授权数据进行缓存(权限管理框架主要就是对认证和授权进行管理,session是在服务器缓存中的),比如将授权数据通过cacheManager进行缓存管理,和ehcache整合对缓存数据进行管理(redis是缓存框架)。
  • realm():域,领域,相当于数据源,通过realm存取认证、授权相关数据(原来是通过数据库取的)。
  • cryptography:密码管理,比如md5加密,提供了一套加密/解密的组件,方便开发。比如提供常用的散列、加/解密等功能。比如 md5散列算法(md5只有加密没有解密)。

2、快速入门

Shiro官网:官网直达
Github项目地址:https://github.com/apache/shiro,
在项目sample——>QuickStart即可找到源代码

1、首先导入maven依赖

<dependencies>
        <dependency>
            <groupId>org.apache.shirogroupId>
            <artifactId>shiro-coreartifactId>
            <version>1.5.2version>
        dependency>

        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>jcl-over-slf4jartifactId>
            <version>1.7.21version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>1.7.21version>
        dependency>
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>  
    dependencies>

2、写一个log4j的配置文档
log4j.properties

log4j.rootLogger=INFO, stdout
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

3、写一个shiro.ini的配置文件
第一次配置时创建不了*ini文件名的的文件,此时idea需要下载InI插件,然后配置就好了。
shiro.ini

[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz

# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5

配置文件说明

配置文件中包含两个部分用户[users]角色[roles]
.
用户配置的格式是: 用户名=密码,角色1,角色2,…角色n
如:root = secret, admin 用户名是 root,密码是secret,拥有角色admin
一个用户可以具有多个角色。注意逗号是英文的。
.
角色配置的格式是: 角色名=权限1,权限2…权限n
如: admin = * 表示admin角色拥有所有权限
role1=perm1,perm2,角色名是role1,拥有perm1和perm2两个权限。

4创建QuickStart类

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;

import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.text.IniRealm;
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;

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:

        // Use the shiro.ini file at the root of the classpath
        // (file: and url: prefixes load from files and urls respectively):
        
        /*Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();*/

        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.
        SecurityUtils.setSecurityManager(defaultSecurityManager);

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

        // get the currently executing user:
        Subject currentUser = SecurityUtils.getSubject();

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        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()) {
            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);
    }
}

踩坑:官方项目里给的介绍是使用IniSecurityManagerFactory,该类上面划横线现在已经过时,不推荐使用,如果这里在创建QucikStart时出现报错等情况,可以采用DefaultSecurityManager类来实现安全管理,本案例默认使用DefaultSecurityManager

		//官方推荐默认代码
        /*Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();*/

		//报错结局方案
		//初始化DefaultSecurityManager 实例
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        //创建一个基于ini文件数据源
        IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
        //将数据绑定到defaultSecurityManager中
        defaultSecurityManager.setRealm(iniRealm);

    	//把defaultSecurityManager实例绑定到securityManager
        SecurityUtils.setSecurityManager(defaultSecurityManager);

在没有报错的情况下就能正常启动运行了。
Shiro快速入门_第2张图片

你可能感兴趣的:(经验记录,shiro)