Shiro-官方文档及使用

普通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

这个声明定义了ServletContextListener启动Shiro环境(包括Shiro环境)。SecurityManager在web应用程序启动时。默认情况下,此侦听器自动知道如何查找WEB-INF/shiro.ini用于Shiro配置的文件。
这个声明定义了主ShiroFilter。这个过滤器需要过滤。全请求进入Web应用程序,这样Shiro可以在允许请求到达应用程序之前执行必要的标识和访问控制操作。
这个声明确保全请求类型由ShiroFilter。经常filter-mapping声明没有指定元素,但是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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: shiro是一个Java开发的开源安全框架,用于进行身份认证、授权和会话管理等安全相关的操作。shiro官方文档是一份详细的介绍和使用指南,有助于开发人员快速了解和掌握shiro使用shiro中文官方文档是针对中国开发者而编写的,文档内容由shiro官方团队进行翻译和整理,确保准确传达原始文档的含义。这份文档包含了shiro的基本概念、核心组件、配置方法以及常见的使用场景等内容。 在官方文档中,首先会介绍shiro的基本概念,如Subject、Realm、Permission等。然后,会阐述如何配置shiro的环境和依赖,在应用程序中引入shiro的相关依赖并进行配置,以实现身份认证和授权的功能。 官方文档还会详细说明如何使用shiro进行身份认证,包括使用自定义的Realm实现用户认证和授权等功能。同时,文档也会指导开发者如何管理用户的会话信息和进行权限控制,以保护应用程序的安全。 此外,官方文档还会提供一些常见的使用场景和示例代码,帮助开发者更好地理解和掌握shiro的实际应用。通过官方文档的阅读和实践,开发者可以加深对shiro的理解,并能够灵活地应用在实际的项目开发中。 总而言之,shiro中文官方文档是一份对于开发者非常有价值的参考材料,可以帮助开发者快速入门和掌握shiro使用方法,提升应用程序的安全性。 ### 回答2: Shiro中文官方文档是一个详细的文档资源,用于帮助理解和使用Shiro安全框架。该文档提供了全面的内容,包括Shiro的基本概念、架构和核心组件,以及如何在实际项目中集成和使用Shiro进行身份验证和授权等功能。 文档的结构清晰,内容组织合理,易于阅读和理解。通过官方文档,我们可以了解到Shiro的整体工作原理和使用方法,它通过模块化的设计可以灵活地满足各种安全需求。 在文档中,我们可以学习如何配置Shiro,包括如何定义用户、角色和权限等信息,并且了解如何使用Shiro提供的各种身份验证和授权机制来保护应用程序的安全性。 此外,文档还提供了丰富的示例代码和解释,帮助我们更好地理解每个功能的实现方式。通过这些示例,我们可以学习到如何使用Shiro来进行常见的安全操作,如用户登录、权限检查和会话管理等。 总的来说,Shiro中文官方文档是一个价值非常高的资源,它为学习和使用Shiro提供了全面的指导。无论是初学者还是有一定经验的开发者,都能从中受益并快速上手使用Shiro框架。 ### 回答3: shiro是一个流行的Java安全框架,用于身份验证、授权和会话管理等安全功能。它提供了一套易于使用和灵活的API,可以帮助开发者快速实现应用程序的安全性。 shiro中文官方文档官方团队为了方便中国开发使用shiro而提供的中文文档。这个文档详细介绍了shiro的各个功能和特性,以及如何在实际项目中使用shiro来保护应用程序的安全性。 文档内容主要包括以下几个方面: 1. 身份验证:介绍了shiro如何进行用户名密码的验证以及其他的身份认证方式,包括基于数据库、LDAP等的认证方式。 2. 授权管理:讲解了如何使用shiro进行细粒度的访问控制,包括角色、权限的管理和配置等。 3. 会话管理:给出了一些关于会话管理的方案,包括基于Cookie、URL重写等的会话跟踪和管理方法。 4. 加密和哈希:详细介绍了如何使用shiro提供的加密和哈希算法来确保用户密码和敏感信息的安全性。 5. 缓存管理:介绍了如何使用shiro提供的缓存功能来提高系统性能和用户体验。 6. 整合和扩展:介绍了如何将shiro与其他框架或技术进行整合,并提供了一些扩展shiro功能的方法。 通过阅读shiro中文官方文档开发者可以了解shiro的基本概念和功能,并且能够清晰地了解如何在自己的项目中使用shiro来提供安全保障。文档中提供了丰富的示例代码和实际应用场景,对初学者来说非常友好。总体来说,shiro中文官方文档是学习和使用shiro的重要指南,对于帮助开发者理解和掌握shiro非常有帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值