shiro框架教程(一) 定义,简单上手
1.什么是shiro框架?
大家都知道,Apache Shiro是一个强大而灵活的开源安全框架,它干净利落地处理身份认证,授权,企业会话管理和加密。
说简单点,该框架主要就是用来认证和授权的。认证:及身份认证,判断你是否是合法用户;授权:及你是否有权限去操作某些资源或者去执行一些功能。更多的定义就不说了,网上一查都有。我们主要是要搞清楚shiro框架怎么认证及授权的。
2.shiro框架的核心。
(1). 图解.首先我们来看一下官方给出的图。
图解:
Subject(org.apache.shiro.subject.Subject)(主体)
当前与软件进行交互的实体,(不一定是用户,也可以是一个程序,一段代码。) SecurityManager(org.apache.shiro.mgt.SecurityManager)(安全管理器)
及安全管理器,从上面的图就可以看到,他是shiro的核心,就像个容器把其他的包裹起来。它管理着当前应用中所有的安全操作,包括Subject(用户),我们围绕Subject展开的所有操作都需要与SecurityManager进行交互。
Authenticator(org.apache.shiro.authc.Authenticator)(认证)
Authenticator是一个对执行及对用户的身份验证(登录)尝试负责的组件。用户认证需要该组件。
Authorizer(org.apache.shiro.authz.Authorizer)(授权)
Authorizer是负责在应用程序中决定用户的访问控制的组件。给用户授权用的,可以分为角色授权和权限授权,角色,及你是管理员,还是普通用户等等。权限授权,及你是否有权限去操作功能(比如说增删改查等)。
SessionManager(org.apache.shiro.session.SessionManager)
SessionManager知道如何去创建及管理用户Session生命周期来为所有环境下的用户提供一个强健的Session体验。这在安全框架界是一个独有的特色——Shiro拥有能够在任何环境下本地化管理用户Session的能力,即使没有可用的Web/Servlet或EJB容器,它将会使用它内置的企业级会话管理来提供同样的编程体验。SessionDAO的存在允许任何数据源能够在持久会话中使用。
SessionDAO(org.apache.shiro.session.mgt.eis.SessionDAO)
SesssionDAO代表SessionManager执行Session持久化(CRUD)操作。这允许任何数据存储被插入到会话管理的基础之中。
CacheManager(org.apahce.shiro.cache.CacheManager)
CacheManager创建并管理其他Shiro组件使用的Cache实例生命周期。因为Shiro能够访问许多后台数据源,由于身份验证,授权和会话管理,缓存在框架中一直是一流的架构功能,用来在同时使用这些数据源时提高性能。任何现代开源和/或企业的缓存产品能够被插入到Shiro来提供一个快速及高效的用户体验。
Cryptography(org.apache.shiro.crypto.*)
Cryptography是对企业安全框架的一个很自然的补充。Shiro的crypto包包含量易于使用和理解的cryptographic Ciphers,Hasher(又名digests)以及不同的编码器实现的代表。所有在这个包中的类都被精心地设计以易于使用和易于理解。任何使用Java的本地密码支持的人都知道它可以是一个难以驯服的具有挑战性的动物。Shiro的cryptoAPI 简化了复杂的Java机制,并使加密对于普通人也易于使用。
Realms(org.apache.shiro.realm.Realm)
如上所述,Realms在Shiro和你的应用程序的安全数据之间担当“桥梁”或“连接器”。当它实际上与安全相关的数据如用来执行身份验证(登录)及授权(访问控制)的用户帐户交互时,Shiro从一个或多个为应用程序配置的Realm中寻找许多这样的东西。你可以按你的需要配置多个Realm(通常一个数据源一个Realm),且Shiro将为身份验证和授权对它们进行必要的协调。
The SecurityManager
因为Shiro的API鼓励一个以Subject为中心的编程方式,大多数应用程序开发人员很少,如果真有,与SecurityManager直接进行交互(框架开发人员有时候会觉得它很有用)。即便如此,了解如何SecurityManager是如何工作的仍然是很重要的,尤其是在为应用程序配置一个SecurityManager的时候。
(本篇博客介绍的不是很详细,更多定义请看:https://www.cnblogs.com/javastack/p/13153193.html)
2.快速上手。
在shiro官网上提供了一个十分中快速入门的案例 ,十分钟快速上手 大家可以看下,接下来我们也试试。
2.1 、打开IDE(最好是idea),创建一个maven项目。导入咋们shiro所需要的依赖。
项目结构截图:
2.2、 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot_shiro</artifactId>
<groupId>com.znzz</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>hello-shiro</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- shiro框架 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.5.3</version>
</dependency>
<!-- configure logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
2.3 、Quickstart.java
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;
/**
* 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:
// Use the shiro.ini file at the root of the classpath
// (file: and url: prefixes load from files and urls respectively):
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
// 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(securityManager);
// 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);
}
}
2.4、 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
2.5、shiro.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
2.6、运行Quick start.java文件。得到如下结果:
你会发现,除了一些打印的日志信息,就没有其他的了。就是这样的。
到这里,你们肯定都是云里雾里的吧,没事。你只需要记住三个核心的概念即可掌握shiro核心!
<1>.Subject: 主体,在项目中一般指的是用户。我们在进行授权鉴权的所有操作都是围绕Subject(用户)展开的,在当前应用的任何地方都可以通过SecurityUtils的静态方法getSubject()拿到当前认证(登录)的用户。
<2>.SecurityManager:安全管理器,shiro的核心,它管理所有的Subject 。比如说用户登录的验证,就需要它。
<3>.Realms:这个是跟数据库打交道的组件。Shiro在进行权限操作时,需要从Realms中获取安全数据,也就是用户以及用户的角色和权限。配置Shiro,我们至少需要配置一个Realms,用于用户的认证和授权。
他们三者之间的关系为:通过SubjectUtils.getSubject(),拿到当前用户,SecurityManager又根据拿到的用户去Realms中获取用户信息(角色、权限等等)。
(这里仅个人见解,不是很清楚,希望大佬给个更清晰的说法,更详细的请看:https://blog.csdn.net/peterwanghao/article/details/8015571)
1.自定义Realms类讲解。
所以,在实际的项目中,我们肯定要自定义realms,
在自定义的realms中,我们要继承AuthorizingRealm抽象类。并实现其中的两个方法,一个认证方法,一个授权方法。
然后在对应的方法里处理对应的逻辑。
2.ShiroConig类的配置
这个类是最主要的。shiro是安全框架嘛,所以你所有的请求,我都要给你拦截下来,你有权限我才给你放行。
这个类里就配置我们的受限资源(要认证才能访问的)、公共资源(所有人都可以访问)、还有密码校验器等等
我就以教程二中的一个例子来讲解:
可以看到,注入了三个Bean , ShiroFilterFactoryBean 、 DefaultWebSecurityManager 、Realm
他们的作用分别是:
- 创建shiroFilter ,负责拦截所有请求。
- 创建安全管理器。
- 创建自定义的realm。
package com.znzz.springboot_jsp_shiro.config;
import com.znzz.springboot_jsp_shiro.shiro.CustomerRealm;
import com.znzz.springboot_jsp_shiro.shiro.RedisCacheManager;
import lombok.val;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.management.MXBean;
import java.util.HashMap;
import java.util.Map;
/**
* 用来整合shiro的配置类
*/
@Configuration
public class ShiroConfig {
//1.创建shiroFilter
//负责拦截所有请求
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//给filter设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
//配置系统的受限资源
Map<String, String> map = new HashMap<String, String>();
map.put("/index.jsp","authc");//authc表示访问这个资源需要认证和授权
map.put("/user/register","anon");
map.put("/register.jsp","anon");//anon表示公共资源,都可以访问的到。
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
//配置系统的公共资源
//默认认证的界面路径,(及你访问没有权限的页面时,会跳转到该页面。)就算你不配置,也会跳转到这个login页面。
shiroFilterFactoryBean.setLoginUrl("/login.jsp");
return shiroFilterFactoryBean;
}
//2.创建安全管理器
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//给安全管理器设置realm
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
//3.创建自定义realm
@Bean
public Realm getRealm(){
CustomerRealm customerRealm = new CustomerRealm();
//修改凭证校验匹配器
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
//设置加密算法为md5
credentialsMatcher.setHashAlgorithmName("MD5");
//设置散列次数
credentialsMatcher.setHashIterations(1024);
customerRealm.setCredentialsMatcher(credentialsMatcher);
//开启缓存管理
//shiro默认的缓存管理器,你也可以存入redis中。该项目没有
customerRealm.setCacheManager(new EhCacheManager());
customerRealm.setCachingEnabled(true);// 开启全局缓存
customerRealm.setAuthenticationCachingEnabled(true);//开启认证缓存
customerRealm.setAuthenticationCacheName("authentication");
customerRealm.setAuthorizationCachingEnabled(true);
customerRealm.setAuthorizationCacheName("authorization");//开启授权的缓存
return customerRealm;
}
}
接下来请看项目实战: