shiro常用配置

快速开始

maven依赖

		<dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.2.3</version>
        </dependency>

配置文件
放在 resources

log4j.properties

#
# 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.
#
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=TRACE

# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

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 'drive' (action) the winnebago (type) with
# winnebago 类型,drive:实列,eagle5:行为
goodguy = winnebago:drive:eagle5

代码

    public static void main(String[] args) {


        //加载配置文件,在web中一般不这样做
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //获取 SecurityManager
        SecurityManager securityManager = factory.getInstance();

        SecurityUtils.setSecurityManager(securityManager);

        //获取Subject
        Subject currentUser = SecurityUtils.getSubject();
        //测试Shiro的Session
        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 + "]");
        }

        // 判断是否授权
        if (!currentUser.isAuthenticated()) {
            //用户名和密码
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true);
            try {
                //进行登陆
                currentUser.login(token);

            } catch (UnknownAccountException uae) {
                log.info("用户名不存在 " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log.info("密码 " + token.getPrincipal() + " 不匹配!");
            } catch (LockedAccountException lae) {
                log.info("用户 " + token.getPrincipal() + " 被锁定.  " +
                        "请解锁用户.");
            }
            catch (AuthenticationException ae) {
                //登陆时其他的错误

            }
        }


        //测试是否包含某个角色
        if (currentUser.hasRole("schwartz")) {
            log.info("包含角色 schwartz !");
        } else {
            log.info("没有权限.");
        }

        // 测试用户是否具备某一个行为. 调用 Subject 的 isPermitted() 方法。
        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.");
        }


        //退出
        currentUser.logout();

        System.exit(0);
    }

整合spring

maven

<dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.3.2</version>
        </dependency>

配置文件,注意配置spring和springMVC
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ 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.
  -->
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <filter>
        <filter-name>CharacterEncodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--shiro -->
    <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>


    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:spring/shiro.xml</param-value>
    </context-param>
    <servlet>
        <servlet-name>app</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>app</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


</web-app>

    

放在resource/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-3.0.xsd">

    <!--
    1.配置securityManager
    -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="cacheManager"/>
        <!-- Single realm app.  If you have multiple realms, use the 'realms' property instead. -->
        <property name="sessionMode" value="native"/>
        <property name="realm" ref="jdbcRealm"/>
    </bean>

    <!--
     2.配置缓存管理器
     -->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:spring/ehcache.xml"/>
    </bean>

    <!--
    3.配置Realm
    -->
    <bean id="jdbcRealm" class="com.learn.myrealm.MyRealm">

    </bean>
    <!--
    4.配置生命周期管理器 可以自动的调用配置在spring IOC容器中的shiro bean 的生命周期方法
    -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    <!--
    5.启用shiro的注解但必须配置lifecycleBeanProcessor
    -->
    <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>

    <!--
    远程调用
    -->
    <!-- Secure Spring remoting:  Ensure any Spring Remoting method invocations can be associated
         with a Subject for security checks. -->
    <bean id="secureRemoteInvocationExecutor" class="org.apache.shiro.spring.remoting.SecureRemoteInvocationExecutor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

    <!--
    6.配置shiroFilter,
      id必须和配置在web.xml的shiro过滤器的名称一致
    -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <!--
            登陆页面
        -->
        <property name="loginUrl" value="/login.jsp"/>
        <!--
           登陆成功页面
        -->
        <property name="successUrl" value="/success.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 overrides or parent/child consolidated configuration
             here if you like: -->
        <!-- <property name="filters">
            <util:map>
                <entry key="aName" value-ref="someFilterPojo"/>
            </util:map>
        </property> -->
        <property name="filterChainDefinitions">
            <value>
                /login.jsp = anon
                # everything else requires authentication:
                /** = authc
            </value>
        </property>
    </bean>

</beans>

ehcache.xml

<!--
  ~ 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.
  -->

<!-- EhCache XML configuration file used for Shiro spring sample application -->
<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

If the path is a Java System Property it is replaced by
its value in the running VM.

The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path -->
    <diskStore path="java.io.tmpdir/shiro-spring-sample"/>


    <!--Default Cache configuration. These will applied to caches programmatically created through
    the CacheManager.

    The following attributes are required:

    maxElementsInMemory            - Sets the maximum number of objects that will be created in memory
    eternal                        - Sets whether elements are eternal. If eternal,  timeouts are ignored and the
                                     element is never expired.
    overflowToDisk                 - Sets whether elements can overflow to disk when the in-memory cache
                                     has reached the maxInMemory limit.

    The following attributes are optional:
    timeToIdleSeconds              - Sets the time to idle for an element before it expires.
                                     i.e. The maximum amount of time between accesses before an element expires
                                     Is only used if the element is not eternal.
                                     Optional attribute. A value of 0 means that an Element can idle for infinity.
                                     The default value is 0.
    timeToLiveSeconds              - Sets the time to live for an element before it expires.
                                     i.e. The maximum time between creation time and when an element expires.
                                     Is only used if the element is not eternal.
                                     Optional attribute. A value of 0 means that and Element can live for infinity.
                                     The default value is 0.
    diskPersistent                 - Whether the disk store persists between restarts of the Virtual Machine.
                                     The default value is false.
    diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value
                                     is 120 seconds.
    memoryStoreEvictionPolicy      - Policy would be enforced upon reaching the maxElementsInMemory limit. Default
                                     policy is Least Recently Used (specified as LRU). Other policies available -
                                     First In First Out (specified as FIFO) and Less Frequently Used
                                     (specified as LFU)
    -->

    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            />

    <!-- We want eternal="true" (with no timeToIdle or timeToLive settings) because Shiro manages session
expirations explicitly.  If we set it to false and then set corresponding timeToIdle and timeToLive properties,
ehcache would evict sessions without Shiro's knowledge, which would cause many problems
(e.g. "My Shiro session timeout is 30 minutes - why isn't a session available after 2 minutes?"
Answer - ehcache expired it due to the timeToIdle property set to 120 seconds.)

diskPersistent=true since we want an enterprise session management feature - ability to use sessions after
even after a JVM restart.  -->
    <cache name="shiro-activeSessionCache"
           maxElementsInMemory="10000"
           eternal="true"
           overflowToDisk="true"
           diskPersistent="true"
           diskExpiryThreadIntervalSeconds="600"/>

    <cache name="org.apache.shiro.realm.SimpleAccountRealm.authorization"
           maxElementsInMemory="100"
           eternal="false"
           timeToLiveSeconds="600"
           overflowToDisk="false"/>

</ehcache>

URL匹配模式

采取第一次匹配优先
? :匹配一个字符
* :匹配零个或多个字符串
** :匹配路径中的零个或多个路径

认证

认证原理

在 Quickstart中有一句代码 currentUser.login(token);在spring中调用此代码时会自动调用继承AuthenticatingRealm中的doGetAuthenticationInfo


加密过程

在UsernamePasswordToken的getUsername()打断点

加密配置

    3.配置Realm
    -->
    <bean id="jdbcRealm" class="com.learn.myrealm.MyRealm">	
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashAlgorithmName" value="MD5"></property>
            </bean>
        </property>
    </bean>

加密使用的类

        String algorithmName="MD5"; //加密算法
        String credentials="123";  //密码
        String salt=null;    //盐值 
        int hashIterations=1;  //加密次数
        SimpleHash simpleHash = new SimpleHash(algorithmName, credentials, salt, hashIterations);
        // 加密后的密码,写入数据库
        System.out.println(simpleHash);

多Realm认证

shiro.xml

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="cacheManager"/>
        <property name="authenticator" ref="authenticator"></property>
    </bean>
	 <!--
    多Realm时配置
    -->
    <bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
        <property name="realms">
            <list>
                <ref  bean="jdbcRealm"/>
                <ref  bean="secondRealm"/>
            </list>
        </property>
    </bean>
 <!--
    3.配置Realm
    -->
    <bean id="jdbcRealm" class="com.learn.myrealm.MyRealm">
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashAlgorithmName" value="MD5"></property>
                <property name="hashIterations" value="1"></property>  <!-- 加密次数 -->
            </bean>
        </property>
    </bean>
    <bean id="secondRealm" class="com.learn.myrealm.SecondRealm">
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashAlgorithmName" value="SHA1"></property>
                <property name="hashIterations" value="1"></property>  <!-- 加密次数 -->
            </bean>
        </property>
    </bean>

多Realm认证策略 ModularRealmAuthenticator 默认是 AtLeastOneSuccessfulStrategy 策略
FirstSuccessfulStrategy:只要有一个Realm验证成功即可,只返回第 一个 Realm 身份验证成功的认证信息,其他的忽略;
AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和 FirstSuccessfulStrategy不同,将返回所有Realm身份验证成功的认证信息;
AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有 Realm身份验证成功的认证信息,如果有一个失败就失败了。

授权

控制能够访问那些资源

方法
编程式:通过写if/else 授权代码块完成 – 注解式:通过在执行的Java方法上放置相应的注解完成,没有权限将抛出相 应的异常
JSP/GSP标签:在JSP/GSP 页面通过相应的标签完成

Shiro中默认的过滤器

public enum DefaultFilter {

    anon(AnonymousFilter.class),
    authc(FormAuthenticationFilter.class),
    authcBasic(BasicHttpAuthenticationFilter.class),
    logout(LogoutFilter.class),
    noSessionCreation(NoSessionCreationFilter.class),
    perms(PermissionsAuthorizationFilter.class),
    port(PortFilter.class),
    rest(HttpMethodPermissionFilter.class),
    roles(RolesAuthorizationFilter.class),
    ssl(SslFilter.class),
    user(UserFilter.class);
}

编程时

//在登陆时currentUser.login(token); 将自动调用用户认证和授权的方法
//也可以调用 currentUser.hasRole("user"); 手动判断
/unauthorized.jsp = roles[user]   <!--  判断是否是user角色 -->


查看是否已经授权
currentUser.hasRole("schwartz")
       
public class MyauthorizedRealm extends AuthorizingRealm {
    
    //用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("MyRealm Realm");
        //1.AuthenticationToken转换为 UsernamePasswordToken
        UsernamePasswordToken authenticationToken1 = (UsernamePasswordToken) authenticationToken;

        //2.从UsernamePasswordToken中来获取username

        //3.查询数据库
        System.out.println("查询出信息");

        //4.用户不存在抛出异常
        if (authenticationToken1.getUsername().equals("1")) {
            throw new UnknownAccountException("用户不存在");
        }

        //5.根据用户信息抛出其他异常

        //6.返回信息
        // 1 principal 数据库的用户名
        // 2 credentials 数据库的密码
        // 3. credentials 盐值 使用唯一不变的信息
        // 4。当前realm 对象的name,调用父类的getName() 方法即可
        ByteSource credentials = ByteSource.Util.bytes("");
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                "123",
                "202cb962ac59075b964b07152d234b70",
                credentials,
                getName());

        //返回后则会进行缓存
        return simpleAuthenticationInfo;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //1.从 PrincipalCollection 中获取登陆用户的信息
        Object primaryPrincipal = principals.getPrimaryPrincipal();

        //2.利用登陆的用户的信息对用户当前的角色或授权
        Set<String> roles = new HashSet<>();
        roles.add("user");
        if ("admin".equals(primaryPrincipal)) {
            roles.add("admin");
        }

        //3.创建 SimpleAuthorizationInfo ,并设置roles 属性
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roles);

        //4.返回 SimpleAuthorizationInfo 对象

        System.out.println("授权中");
        return simpleAuthorizationInfo;
    }
}

身份相关的拦截器

默认拦截器名拦截器类说明
authcFormAuthenticationFilter基于表单的拦截器;如“/**=aythc”,如果没有登陆就会跳转到相应的登陆页面;主要属性:usernameParam:表单提交的用户名参数名
authcBasicBasicHttpAuthenticationFilterBasic HTTP身份验证拦截器,主要属性:applicationName:弹出登陆框信息(application)
logoutLogoutFilter退出拦截器,主要属性:redirectUrl:退出重定向地址
userUserFilter用户拦截器,用户已经身份验证/记住我登陆的都可;配置如 “/**=user”
annoAnonymousFilter匿名拦截器,不需要登陆就能访问
rolesRolesAuthorizationFilter角色拦截器,验证用户是否拥有某角色,主要属性:loginUrl:登陆页面;unauthorizedUrl:未授权后重定向的地址 ;配置如:“/**=roles[user]”
permsPermissionsAuthorizationFilter权限拦截去,验证用户是否拥有某行为,属性和roles一样;配置如:“/**=perms[user:add]”
portPortFilter端口拦截去,主要属性:prot(80);可以通过的端口;实例“/**=port[80]” ,如果用户访问该页面不是80端口,将自动将请求端口改为80并重定向到该80端口,其他路径/参数都一样
restHttpMethodPermissionFilterrest风格拦截器,自动根据请求方法构建权限字符串(GET=read,POST=create,PUT=update,DELETE=delete,HEAD=read,TRACE=read,OPTIONS=read,MKCOL=create)构建权限字符串;如:“/users=rest[user]”,会自动拼出user:read,user:create,user:update,user:delete 权限字符串进行权限匹配(所有都得匹配,isPermittedAll)
sslSslFilterSSL拦截器,只有请求协议为https 才能通过;否则自动跳转到https端口(443);其他和port拦截器一样
noSessionCreationNoSessionCreationFilter不创建会话连接器。调用subject.getSession(false)不会出问题,但如果subject.getSession(true)将抛异常

授权流程

Shiro标签

在jsp页面引入
<%@ taglib prefix=“shiro” uri=“http://shiro.apache.org/tags” %>

Shiro注解

@RequiresAuthentication:表示当前Subject已经通过login
进行了身份验证;即 Subject. isAuthenticated() 返回 true
@RequiresUser:表示当前 Subject 已经身份验证或者通过记
住我登录的。
@RequiresGuest:表示当前Subject没有身份验证或通过记住
我登录过,即是游客身份。
@RequiresRoles(value={“admin”, “user”}, logical=
Logical.AND):表示当前 Subject 需要角色 admin 和user
@RequiresPermissions (value={“user:a”, “user:b”},
logical= Logical.OR):表示当前 Subject 需要权限 user:a 或
user:b。

注: 如果Serive层有@transaction注解时,这个Service已经是一个代理对象了,shiro注解再加到Service层时会失效

在java代码中配置权限

java

package com.learn.factory;

import java.util.LinkedHashMap;

public class AuFactory {

    public LinkedHashMap<String,String> getfilterChainDefinitions(){
        System.out.println("------");
        LinkedHashMap<String,String> map=new LinkedHashMap<>();
        map.put("/login.jsp","anon");
        map.put("/hello","anon");
        map.put("/logout","logout");
        map.put("/**","authc");
        return map;

    }

}

shiro.xml

 <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <!--
            登陆页面
        -->
        <property name="loginUrl" value="/login.jsp"/>
        <!--
           登陆成功页面
        -->
        <property name="successUrl" value="/success.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 overrides or parent/child consolidated configuration
             here if you like: -->
        <!-- <property name="filters">
            <util:map>
                <entry key="aName" value-ref="someFilterPojo"/>
            </util:map>
        </property> -->

        <property name="filterChainDefinitionMap" ref="map"></property>
        <!-- 注释掉在配置文件中的配置 -->
        <!--<property name="filterChainDefinitions">
            <value>
                /login.jsp = anon
                /hello = anon
                /logout = logout
                /unauthorized.jsp = roles[user]   &lt;!&ndash;  授权 &ndash;&gt;
                /** = authc
            </value>
        </property>-->
    </bean>

    <bean id="map" factory-bean="auFactory" factory-method="getfilterChainDefinitions"></bean>

    <!-- 实例工厂类构建一个Map -->
    <bean id="auFactory" class="com.learn.factory.AuFactory">

    </bean>

shiro会话

能在Service层通过Shiro的Session获取Http的Session

SessionDao

能将Session写入数据库

认证和记住我

配置
token.setRememberMe(true); //代码中
map.put("/url",“user”); //使用AnonymousFilter过滤器
认证和记住我只能选择其一

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值