Apache Shiro是java的一个安全(权限)框架。Shiro可以非常容易的开发出足够好的应用,在javase和javaee环境都可以使用。Shiro可以完成:认证,授权,加密,会话管理,与WEB集成,缓存等。
Shiro架构(外部):
Subject:应用代码直接交互的对象是subject,Subject代表了当前“用户”。与Subject的所有交互都会委托给SecurityManager。Subject其实是一个门面,SecurityManager才是实际的执行者。
SecurityManager:安全管理器,即所有与安全有关的操作都会与SecurityManager交互。是Shiro的核心,它负责与Shiro的其他组件交互。相当于SpringMVC的DispatcherServlet的角色。
Realm:Shiro从Realm获取安全数据(如用户、角色、权限)
Shiro架构(内部):
Authenticator:负责Subject认证,可以自定义实现,可以使用认证策略,即什么情况下用户可以认证通过。
Authorizer:授权器,控制着用户能访问应用中的哪些功能。
SessionManager:管理Session生命周期的组件。
CacheManager:缓存控制器,管理用户、角色权限等的缓存的。
Cryptography:密码模块。常用的加密和解密操作。
权限注解:
以下代码的项目地址:https://gitee.com/sexylalal/shiro_test1.git
基本依赖jar包
<dependencies>
<!--单元测试junit jar-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--日志管理-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<!--shiro start-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>1.3.2</version>
</dependency>
<!--shiro end-->
<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.4</version>
</dependency>
<!--spring start-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!--spring end-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
</dependencies>
web.xml shiro启动入口:
<!--
第一步 配置shiro
DelegatingFilterProxy实际上是Filter的一个代理对象,默认情况下,Spring会到IOC容器中查找和
<filter-name> 对应的filter bean 。 也可以通过targetBeanName的初始化参数类配置filter bean 的id
-->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
主要配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--1.配置 SecurityManager-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<!--<property name="realm" ref="jdbcRealm"/>-->
<property name="authenticator" ref="authenticator"/>
<property name="realms">
<list>
<!--<ref bean="shiroRealm"/>-->
<ref bean="manyRealm"/>
</list>
</property>
</bean>
<!--2.配置cacheManager-->
<!--2.1需要加入ehCache的配置文件-->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<!--<property name="cacheManager" ref="ehCacheManager"/>-->
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="authenticationStrategy">
<!--
认证策略 有三种方式
默认:AtLeastOneSuccessfulStrategy 只要有一个Realm认证成功即可通过
FilstSuccessfulStrategy 只要有一个认证成功 只返回一个Realm的成功信息 其他的忽略
AllSuccessfulStrategy 所有Realm都要认证成功 且返回所有认证信息
-->
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy">
</bean>
</property>
</bean>
<!--
3配置realm
3.1直接配置实现了Realm接口的bean
-->
<bean id="shiroRealm" class="com.lechisoft.shiro.ShiroRealm">
<!--MD5加密 from表单 输入的密码-->
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"></property>
<!--加密1024次-->
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>
<bean id="manyRealm" class="com.lechisoft.shiro.ManyRealm">
<!--MD5加密 from表单 输入的密码-->
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="SHA1"></property>
<!--加密1024次-->
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>
<!--4 配置LifecycleBeanPostProcessor 可以自动的来配置在SpringAoc 容器中 shiro bean的声明周期的方法-->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!--5. 启动IOC容器中的shiro的注解。 但必须配置了LifecycleBeanPostProcessor之后才能使用-->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<!--
6配置ShiroFilter
6.1 id必须和web.xml 文件中配置的DelegatingFilterProxy的<filter-name> 值一致
-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/views/login.jsp"/>
<property name="successUrl" value="/views/list.jsp"/>
<!--没有权限的页面-->
<property name="unauthorizedUrl" value="/views/unauthorized.jsp"/>
<!--
配置哪些页面需要受到保护 可以查看org.apache.shiro.web.filter.mgt.DefaultFilter类 有哪些配置信息
以及访问这些页面需要的权限
anon 可以匿名访问,不需要认证
authc 必须认证 (即登录)后才能访问
logout 登出
?匹配单个字符 *匹配零或多个字符串 **匹配路径中的零个或多个路径
roles 角色过滤器
-->
<property name="filterChainDefinitionMap" ref="filterChainDefinitionMap">
</property>
<!--
<property name="filterChainDefinitions">
<value>
/views/login.jsp = anon
/shiro/login = anon
/shiro/logout = logout
/views/user.jsp = roles[user]
/views/admin.jsp = roles[admin]
# everything else requires authentication:
/** = authc
</value>
</property>
-->
</bean>
<!--配置一个bean 该bean实际上是一个Map 通过实例工厂的方式-->
<bean id="filterChainDefinitionMap" factory-bean="filterChainDefinitionMapBuilder"
factory-method="builderFilterChainDefinitionMap">
</bean>
<bean id="filterChainDefinitionMapBuilder"
class="com.lechisoft.factory.FilterChainDefinitionMapBuilder">
</bean>
<bean id="shiroService" class="com.lechisoft.services.ShiroService">
</bean>
</beans>
eacache.xml文件
<ehcache>
<diskStore path="java.io.tmpdir"/>
<cache name="authorizationCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="0"
overflowToDisk="false"
statistics="true">
</cache>
<cache name="authenticationCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="0"
overflowToDisk="false"
statistics="true">
</cache>
<cache name="shiro-activeSessionCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="0"
overflowToDisk="false"
statistics="true">
</cache>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<cache name="sampleCache1"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<cache name="sampleCache2"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>
</ehcache>
ManyRealm和ShiroRealm分别为两个角色,基本操作相同。根据业务进行修改。
ManyRealm类:
package com.lechisoft.shiro;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ManyRealm extends AuthorizingRealm {
/**
* 用户授权的方法
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {
System.out.println("[ManyRealm]doGetAuthenticationInfo");
//1.把AuthenticationToken转换为UsernamePasswordToken
UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
//2.从UsernamePasswordToken中获取username
String username = token.getUsername();
//3.调用数据库的方法,从数据库中查询username对应的用户记录
System.out.println("从数据库中获取username:"+username+"所对应的用户信息");
//4.若用户不存在,则可以抛出UnknownAccountException
if("unknown".equals(username)){
throw new UnknownAccountException("用户不存在");
}
//5.根据用户的信息情况,决定是否抛出其他异常
if("monster".equals(username)){
throw new LockedAccountException("用户被锁定");
}
//6.根据用户的情况,来构建AuthenticationInfo对象并返回,通常的实现类是SimpleAuthenticationInfo
//以下信息是从数据库中获取的
//(1). principal 认证的实体类信息。可以是username 也可以是数据表中对应的用户实体类对象
Object principal = username;
//(2).credentials:密码
Object credentials = null;
if("user".equals(username)){
credentials = "073d4c3ae812935f23cb3f2a71943f49e082a718";
}else if("admin".equals(username)){
credentials = "ce2f6417c7e1d32c1d81a797ee0b499f87c5de06";
}
//(3).realmName:当前realm对象的name 调用父类getName() 方法即可
String realmName = getName();
// AuthenticationInfo info= new SimpleAuthenticationInfo(principal, credentials, realmName);
//(4).盐值
ByteSource salt = ByteSource.Util.bytes(username);
AuthenticationInfo info= new SimpleAuthenticationInfo(principal,credentials,salt,realmName);
return info;
}
/**
* 用于授权
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//1.从PrincipalCollection中来获取用户信息
Object principal = principalCollection.getPrimaryPrincipal();
//2.利用登录的用户信息来获取用户权限和角色(可能需要查询数据库)
Set<String> roles = new HashSet<String>();
roles.add("user");
if("admin".equals(principal)){
roles.add("admin");
}
//3.创建SimpleAuthorizationInfo,并设置reles属性
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
return info;
}
}
测试:
@RequestMapping("/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password){
Subject subject = SecurityUtils.getSubject();
//测试当前的用户是否已经被认证. 即是否已经登录.
if(!subject.isAuthenticated()){
/**没有被认证 需要给一个token**/
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
token.setRememberMe(true);
try {
subject.login(token);
}catch (IncorrectCredentialsException e1){
System.out.println("密码错误:"+e1);
//AuthenticationException 所有认证时异常的父类
} catch (AuthenticationException e){
System.out.println("登录失败:"+e);
}
}
return "redirect:/views/list.jsp";
}
官方提供的测试文件(Quickstart和shiro.ini)可直接运行测试:
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. 调用 SecurityUtils.getSubject();
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
// 测试使用 Session
// 获取 Session: Subject#getSession()
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:
// 测试当前的用户是否已经被认证. 即是否已经登录.
// 调动 Subject 的 isAuthenticated()
if (!currentUser.isAuthenticated()) {
// 把用户名和密码封装为 UsernamePasswordToken 对象
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
// remember me
token.setRememberMe(true);
try {
// 执行登录.
currentUser.login(token);
}
// 若没有指定的账户, 则 shiro 将会抛出 UnknownAccountException 异常.
catch (UnknownAccountException uae) {
log.info("----> There is no user with username of " + token.getPrincipal());
return;
}
// 若账户存在, 但密码不匹配, 则 shiro 会抛出 IncorrectCredentialsException 异常。
catch (IncorrectCredentialsException ice) {
log.info("----> Password for account " + token.getPrincipal() + " was incorrect!");
return;
}
// 用户被锁定的异常 LockedAccountException
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:
// 测试是否有某一个角色. 调用 Subject 的 hasRole 方法.
if (currentUser.hasRole("schwartz")) {
log.info("----> May the Schwartz be with you!");
} else {
log.info("----> Hello, mere mortal.");
return;
}
//test a typed permission (not instance-level)
// 测试用户是否具备某一个行为. 调用 Subject 的 isPermitted() 方法。
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("user:delete:zhangsan")) {
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!
// 执行登出. 调用 Subject 的 Logout() 方法.
System.out.println("---->" + currentUser.isAuthenticated());
currentUser.logout();
System.out.println("---->" + currentUser.isAuthenticated());
System.exit(0);
}
}
shiro.ini
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# =============================================================================
# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[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 'delete' (action) the user (type) with
# license plate 'zhangsan' (instance specific id)
goodguy = user:delete:zhangsan