普通web应用官方文档:
shiro.ini
Once you choose at least one user store to connect to for Shiro’s needs, we’ll need to configure a Realm that represents that data store and then tell the ShiroSecurityManager about it.
If you’ve checked out the step2 branch, you’ll notice the src/main/webapp/WEB-INF/shiro.ini file’s [main] section now has the following additions:
中文翻译:一旦您为Shiro的需要选择了至少一个要连接到的用户商店,我们将需要配置一个Realm,它表示数据存储,然后告诉ShiroSecurityManager关于这件事。
如果您已经检查了step2布兰奇,你会注意到src/main/webapp/WEB-INF/shiro.ini档案[main]一节现在增加了以下内容
# Configure a Realm to connect to a user datastore. In this simple tutorial,
# we'll just point to Stormpath since it
# takes 5 minutes to set up:
stormpathClient = com.stormpath.shiro.client.ClientFactory
stormpathClient.cacheManager = $cacheManager
# (Optional) If you put your apiKey.properties in the non-default location, you set the location here
#stormpathClient.apiKeyFileLocation = $HOME/.stormpath/apiKey.properties
stormpathRealm = com.stormpath.shiro.realm.ApplicationRealm
stormpathRealm.client = $stormpathClient
# Find this URL in your Stormpath console for an application you create:
# Applications -> (choose application name) --> Details --> REST URL
# (Optional) If you only have one Application
# stormpathRealm.applicationRestUrl = https://api.stormpath.com/v1/applications/$STORMPATH_APPLICATION_ID
stormpathRealm.groupRoleResolver.modeNames = name
securityManager.realm = $stormpathRealm
web.xml
这个<listener>声明定义了ServletContextListener启动Shiro环境(包括Shiro环境)。SecurityManager在web应用程序启动时。默认情况下,此侦听器自动知道如何查找WEB-INF/shiro.ini用于Shiro配置的文件。
这个<filter>声明定义了主ShiroFilter。这个过滤器需要过滤。全请求进入Web应用程序,这样Shiro可以在允许请求到达应用程序之前执行必要的标识和访问控制操作。
这个<filter-mapping>声明确保全请求类型由ShiroFilter。经常filter-mapping声明没有指定<dispatcher>元素,但是Shiro需要定义它们,这样它就可以过滤可能为Web应用程序执行的所有不同的请求类型。
<listener>
<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>
<filter>
<filter-name>ShiroFilter</filter-name>
<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ShiroFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
spring整合shiro官方文档
web.xml:
<!-- The filter-name matches name of a 'shiroFilter' bean inside applicationContext.xml -->
<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>
<!-- Make sure any request you want accessible to Shiro is filtered. /* catches all -->
<!-- requests. Usually this filter mapping is defined first (before all others) to -->
<!-- ensure that Shiro works in subsequent filters in the filter chain: -->
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
applicationContext.xml
bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!--配置引用安全管理器-->
<property name="securityManager" ref="securityManager"/>
<!-- override these for application-specific URLs if you like:
<!--配置登录页面-->
<property name="loginUrl" value="/login.jsp"/>
<!--配置成功登录后跳转的页面-->
<property name="successUrl" value="/home.jsp"/>
<!--配置拦截后跳转的页面-->
<property name="unauthorizedUrl" value="/unauthorized.jsp"/> -->
<!-- The 'filters' property is not necessary since any declared javax.servlet.Filter bean -->
<!-- defined will be automatically acquired and available via its beanName in chain -->
<!-- definitions, but you can perform instance overrides or name aliases here if you like: -->
<!-- <property name="filters">
<util:map>
<entry key="anAlias" value-ref="someFilter"/>
</util:map>
</property> -->
<!--配置过滤器规则
常用的规则:
anno:任何人可以访问
authc:必须登录后才能访问,不包括remember me
user:登录用户才可以访问,包含remember me
perms:指定过滤规则,这个一般是扩展使用,不会使用原生的
-->
<property name="filterChainDefinitions">
<value>
# some example chain definitions:
/admin/** = authc, roles[admin]
/docs/** = authc, perms[document:read]
/** = authc
# more URL-to-FilterChain definitions here
</value>
</property>
</bean>
<!-- Define any javax.servlet.Filter beans you want anywhere in this application context. -->
<!-- They will automatically be acquired by the 'shiroFilter' bean above and made available -->
<!-- to the 'filterChainDefinitions' property. Or you can manually/explicitly add them -->
<!-- to the shiroFilter's 'filters' Map if desired. See its JavaDoc for more details. -->
<bean id="someFilter" class="..."/>
<bean id="anotherFilter" class="..."> ... </bean>
...
<!--配置安全管理器-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!-- Single realm app. If you have multiple realms, use the 'realms' property instead. -->
<property name="realm" ref="myRealm"/>
<!-- By default the servlet container sessions will be used. Uncomment this line
to use shiro's native sessions (see the JavaDoc for more): -->
<!-- <property name="sessionMode" value="native"/> -->
</bean>
<!--生命周期管理-->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- Define the Shiro Realm implementation you want to use to connect to your back-end -->
<!-- security datasource: -->
<!--配置realm-->
<bean id="myRealm" class="...">
...
</bean>
启用Shiro注释
<!-- Enable Shiro Annotations for Spring-configured beans. Only run after -->
<!-- the lifecycleBeanProcessor has run: -->
<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>
在spring整合shiro过程中,不需要添加EnvironmentLoaderListener这个监听器,是因为spring的ContentLoadListener 已经代替EnvironmentLoaderListener初始化容器并加载配置shiro的配置文件,所以spring整合shiro以后不需要配置EnvironmentLoaderListener。
使用
依赖:
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!--shiro核心包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
web.xml:
<!--4. Shiro权限校验过滤器,这里的filter-name固定,对应spring容器中的过滤器工厂的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>
自定义realm类
package com.zhijin.web.shiro;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
/**
* 自定义reamlm
*/
public class AuthRealm extends AuthorizingRealm {
//登陆认证
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//强转为用户名密码token
UsernamePasswordToken upToken = (UsernamePasswordToken)token;
//得页面传的登录名
String email = upToken.getUsername();
//从数据库中查询登录名
User user = userService.findUserByEmail(email);
if (user != null){
//封装到认证对象中
//第一个参数:安全数据(user对象)
//第二个参数:密码(数据库密码)
//第三个参数:当前调用realm域的名称(类名即可)
return new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
}
return null;
}
// 授权访问校验
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
User user = (User) principals.getPrimaryPrincipal();
if (user !=null) {
//根据用户的ID从数据库中查询出权限模块
List<Module> moduleList = moduleService.findModuleByUserId(user.getId());
Set<String> permissions = new HashSet<>();
for (Module module : moduleList) {
//将查询出的模块名称添加到set集合中
permissions.add(module.getName());
}
SimpleAuthorizationInfo sia = new SimpleAuthorizationInfo();
//将带有模块名称的set结合添加到SimpleAuthorizationInfo(封装授权对象)
sia.addStringPermissions(permissions);
return sia;
}
return null;
}
}
配置applicationContext-shiro
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 1. 配置shiro过滤器工厂 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!--配置引用安全管理器-->
<property name="securityManager" ref="securityManager"/>
<!--登录页面-->
<property name="loginUrl" value="/login.jsp"/>
<!--没有权限默认跳转的页面,登录的用户访问了没有被授权的资源自动跳转到的页面-->
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>
<!--配置过滤规则-->
<property name="filterChainDefinitions">
<value>
<!--
anno:任何人可以访问
authc:必须登录后才能访问,不包括remember me
user:登录用户才可以访问,包含remember me
perms:指定过滤规则,这个一般是扩展使用,不会使用原生的
-->
/index.jsp* = anon
/login.jsp* = anon
/login* = anon
/logout* = anon
/css/** = anon
/img/** = anon
/plugins/** = anon
/make/** = anon
/** = authc
</value>
</property>
</bean>
<!--2. 配置安全管理器-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"/>
</bean>
<!--3. 配置自定义Realm域 -->
<bean id="myRealm" class="com.zhijin.web.shiro.AuthRealm">
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>
<!--4. 创建shiro提供的凭证匹配器,自动对用户输入的密码按照指定的算法加密-->
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="md5"/>
</bean>
</beans>
自定义凭证匹配器
package com.zhijin.web.shiro;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.Md5Hash;
public class CustomCredentialsMatcher extends HashedCredentialsMatcher {
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
//获取用户输入的登录名
String username = (String) token.getPrincipal();
//获取用户输入的登录密码
String password = new String((char[])token.getCredentials());
//获取数据库查出来的密码
String md5Password = new Md5Hash(password,username).toString();
String dbPassword = (String) info.getCredentials();
return md5Password.equals(dbPassword);
}
}
登录
//1.获取subject
Subject subject = SecurityUtils.getSubject();
//2.构造用户名和密码
UsernamePasswordToken upToken = new UsernamePasswordToken(email, password);
//3.借助subject完成用户登录
subject.login(upToken);