1.导入POM文件
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
2. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<--! DelegatingFilterProxy 作用是自动到 Spring容器查找名字为 shiroFilter(filter-name)
的 bean 并把所有 Filter的操作委托给它 -->
<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>
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
注:DelegatingFilterProxy的filter-name要和spring-shiro中的shiroFilterFactoryBean中的id相同,否则报错,或者使用以下方法(在DelegatingFilterProxy中加入<init-param>)
<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>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>name</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
此时spring-shiro中的shiroFilterFactoryBean中的id和param-value相同,即name
3.spring-shiro.xml
<?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">
<bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"></bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"></property>
<property name="authenticator" ref="authenticator"></property>
<property name="rememberMeManager" ref="rememberManager"></property>
<property name="realms">
<list>
<ref bean="firstRealm"></ref>
<ref bean="secondRealm"></ref>
</list>
</property>
</bean>
<!--配置realm认证策略-->
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="authenticationStrategy">
<!-- <bean class="org.apache.shiro.authc.pam.FirstSuccessfulStrategy"></bean>-->
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
<!--<bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"></bean>-->
</property>
</bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"></property>
<property name="loginUrl" value="/login"></property>
<property name="successUrl" value="/success"></property>
<property name="unauthorizedUrl" value="/error"></property>
<!--filterChainDefinitionMap和filterChainDefinitions只能存在一个-->
<property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"></property>
<!-- <property name="filterChainDefinitions">
<value>
/logout=logout
/doLogin=anon
/admin=roles[admin]
/user=roles[user]
/vip=roles[vip]
/**=authc
</value>
</property>-->
</bean>
<!--设置cookie-->
<bean id="rememberCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="jizhuwo"></constructor-arg>
<property name="httpOnly" value="true"></property>
<property name="maxAge" value="100"></property>
</bean>
<!--记住我配置-->
<bean id="rememberManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
<property name="cookie" ref="rememberCookie"></property>
</bean>
<bean id="firstRealm" class="com.shiro.realms.FirstRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!--加密算法-->
<property name="hashAlgorithmName" value="MD5"></property>
<!--加密次数-->
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>
<bean id="secondRealm" class="com.shiro.realms.SecondRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="SHA1"></property>
<property name="hashIterations" value="1024"/>
</bean>
</property>
</bean>
<!--注解生效-->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true"/>
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<!--buildFilterChainDefinitionMap实例工厂-->
<bean id="filterChainDefinitionMapFactory" class="com.shiro.factory.FilterChainDefinitionMapFactory"></bean>
<bean id="filterChainDefinitionMap" factory-bean="filterChainDefinitionMapFactory"
factory-method="buildFilterChainDefinitionMap"></bean>
</beans>
4.Controller
@RequestMapping("/doLogin")
public String doLogin(String username, String password) {
System.out.println("doLogin.............");
Subject subject= SecurityUtils.getSubject();
if(!subject.isAuthenticated()){
UsernamePasswordToken token=new UsernamePasswordToken(username,password,true);
try {
subject.login(token);
} catch (AuthenticationException e) {
System.out.println("认证失败。");
}
}
return "redirect:success";
}
5.realm
public class FirstRealm extends AuthorizingRealm{
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken uptoken=(UsernamePasswordToken) token;
String username = uptoken.getUsername();
String credentials=null;
if("zhangsan".equals(username)){
credentials="2a0d136ceacafe198ea64ac09daaf1b6";
}else if("lisi".equals(username)){
credentials = "8c702ae443795331c91cfab48f3f3833";
}
ByteSource byteSource=new ByteSource.Util().bytes(username);
AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, credentials, byteSource, getName());
// new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
return authenticationInfo;
}
public static void main(String[] args) {
String hashAlgorithmName = "MD5";
Object credentials = "123456";
Object salt = ByteSource.Util.bytes("lisi");;
int hashIterations = 1024;
Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
System.out.println(result);
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("FirstRealm..2222.........");
Object primaryPrincipal = principals.getPrimaryPrincipal();
Set<String> roles = new HashSet<>();
if("zhangsan".equals(primaryPrincipal)){
roles.add("user");
roles.add("vip");
}else if("abc".equals(primaryPrincipal)){
roles.add("user");
}
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addRoles(roles);
return simpleAuthorizationInfo;
}
}
public class SecondRealm extends AuthorizingRealm{
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken uptoken=(UsernamePasswordToken) token;
String username = uptoken.getUsername();
String credentials=null;
if("abc".equals(username)){
credentials="31420b87dd2e42f39d7dc7bdc3a7ee12e4053de8";
}else if("qwe".equals(username)){
credentials = "466c492b84308fb956c6d1acf4301743cbc19037";
}
ByteSource byteSource=new ByteSource.Util().bytes(username);
AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, credentials, byteSource, getName());
// new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
return authenticationInfo;
}
public static void main(String[] args) {
String hashAlgorithmName = "SHA1";
Object credentials = "123";
Object salt = ByteSource.Util.bytes("qwe");;
int hashIterations = 1024;
Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
System.out.println(result);
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("secondRealm...。。。..........");
Object primaryPrincipal = principals.getPrimaryPrincipal();
Set<String> roles = new HashSet<>();
if("zhangsan".equals(primaryPrincipal)){
roles.add("admin");
}else if("abc".equals(primaryPrincipal)){
roles.add("admin");
}
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roles);
return simpleAuthorizationInfo;
}
}
- 自定义的realm继承AuthorizingRealm就可以实现认证和授权方法,AuthorizingRealm继承自AuthenticatingRealm,AuthenticatingRealm中有doGetAuthenticationInfo方法,AuthorizingRealm中有doGetAuthorizationInfo
- realm的认证策略:
- FirstSuccessfulStrategy:只要有一个 Realm 验证成功即可,只返回第一个 Realm 身份验证成功的认证信息,其他的忽略;
- AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和FirstSuccessfulStrategy 不同,将返回所有Realm身份验证成功的认证信息;(默认策略)
- AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有Realm身份验证成功的认证信息,如果有一个失败就失败了。
- 因为缓存:先去第一个realm寻找role,如果第一个realm有放入当前页面的权限就不继续访问下一个realm,当继续访问其他页面而第一个realm没有放入当前页面的role,则去第二个realm寻找。(不会重复访问,不配置缓存就会重复访问)
- filterChainDefinitionMap工厂(filterChainDefinitionMap和filterChainDefinitions只能存在一个)
public class FilterChainDefinitionMapFactory {
public LinkedHashMap<String,String> buildFilterChainDefinitionMap(){
LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("/doLogin", "anon");
map.put("/logout", "logout");
map.put("/admin", "authc,roles[admin]");
map.put("/user", "roles[user]");
map.put("/test", "user");
map.put("/vip", "user");
map.put("/success", "user");
map.put("/**", "authc");
return map;
}
}
rememberMe功能如果要认证才可以操作的的除了加权限还要加authc 例如:map.put("/admin", "authc,roles[admin]");否则可以通过记住我直接访问/admin
shiro权限注解
- @RequiresAuthentication:表示当前Subject已经通过login进行了身份验证;即 Subject. isAuthenticated() 返回 true
- @RequiresUser:表示当前 Subject 已经身份验证或者通过记住我登录的。
- @RequiresGuest:表示当前Subject没有身份验证或通过记住我登录过,即是游客身份。
- @RequiresRoles(value={“admin”, “user”}, logical= Logical.AND):表示当前 Subject 需要角色 admin 和user,@RequiresRoles(value={“admin”, “user”}, logical= Logical.OR):表示当前 Subject 需要角色 admin 或user中的其中一个
- @RequiresPermissions (value={“user:a”, “user:b”}, logical= Logical.OR):表示当前 Subject 需要权限 user:a 或user:b。
@RequiresRoles(value = {"admin","vip"},logical = Logical.AND)
@RequestMapping(value = {"/testAnnotation2"})
public String testAnnotation2(){
System.out.println("testAnnotation2222。");
return "success";
}
如果要在Controller层使用注解,要在springmvc.xml中添加
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
如果要在service中使用,在spring-shiro中即可
httpsession和SecurityUtils.getSubject().getSession()可以互相改,可以在service调用session
session也有会话监听器用于监听会话创建、过期及停止事件onStart,onStop,onexpiration