前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Shiro 配置

Shiro 配置

作者头像
疯狂的KK
发布2020-02-19 11:23:40
6200
发布2020-02-19 11:23:40
举报
文章被收录于专栏:Java项目实战Java项目实战

Shiro的demo能够体验根据配置文件,达到是否能够登陆的效果,除此之外,Shiro整合Spring来达到实际使用场景。

同样的打开

代码语言:javascript
复制
shiro-root-1.3.2\samples\spring\src\main\webapp\WEB-INF下
applicationContext.xml以及web.xml

配置文件解析

配置用户与角色之间的关系

代码语言:javascript
复制
   </bean>
    <!-- Populates the sample database with sample users and roles. -->
    <bean id="bootstrapDataPopulator" class="org.apache.shiro.samples.spring.BootstrapDataPopulator">
        <property name="dataSource" ref="dataSource"/>
    </bean>

Shiro的三大组件

代码语言:javascript
复制
//shiro的核心组件 
  SecurityManager 三个属性
  1.cacheManager
  1.1加入ehcahche的jar包
  2.sessionMode
  3.realm
    <!-- =========================================================
         Shiro Core Components - Not Spring Specific
         ========================================================= -->
    <!-- Shiro's main business-tier object for web-enabled applications
         (use DefaultSecurityManager instead when there is no web environment)-->
    <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>

realm实现

org.apache.shiro.realm.Realm下的Realm

代码语言:javascript
复制
package com.kk;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.realm.Realm;

/**
 * @author zhaokk
 * @create 2020-02-01-20:26
 */
public class ShiroRealm implements Realm {
    public String getName() {
        return null;
    }

    public boolean supports(AuthenticationToken authenticationToken) {
        return false;
    }

    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        return null;
    }
}

Life生命周期bean

代码语言:javascript
复制
4.0 bean生命周期器的管理器自动调用配置SpringIoc中的Shiro
  的生命周期方法
    <!-- =========================================================
         Shiro Spring-specific integration
         ========================================================= -->
    <!-- Post processor that automatically invokes init() and destroy() methods
         for Spring-configured Shiro objects so you don't have to
         1) specify an init-method and destroy-method attributes for every bean
            definition and
         2) even know which Shiro objects require these methods to be
            called. -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

启用注解

代码语言:javascript
复制
  //5.0启用IOC容器中使用shiro的注解  但必须在配置LifecycleBeanPostProcessor 才可使用
    <!-- 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>
代码语言:javascript
复制
   以filter命名  有点像过滤器的效果
   //6.0 id必须和web.xml  filtername一致
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/s/login"/>
        <property name="successUrl" value="/s/index"/>
        <property name="unauthorizedUrl" value="/s/unauthorized"/>
        <!-- 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>
                /favicon.ico = anon   //过滤器  可以匿名访问
                /logo.png = anon
                /shiro.css = anon
                /s/login = anon
                # allow WebStart to pull the jars for the swing app:
                /*.jar = anon
                # everything else requires authentication:
                /** = authc   //通配符表示认证后才可访问
            </value>
        </property>
    </bean>

在web.xml中拦截想要过滤的页面

代码语言:javascript
复制
  <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>

在applicationcontext.xml中shiroFilter的id要与web.xml中的filtername一致

代码语言:javascript
复制
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
代码语言:javascript
复制
 <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>

否则会抛出异常NoSuchBeanDifinationException

在org.springframework.web.filter中配置在web.xml里的Filter

代码语言:javascript
复制
import org.springframework.web.filter.DelegatingFilterProxy;

打开源码看下如何访问web.xml

代码语言:javascript
复制

支持使用fitername 找相应的bean

/**
 * Proxy for a standard Servlet Filter, delegating to a Spring-managed bean that
 * implements the Filter interface. Supports a "targetBeanName" filter init-param
 * in {@code web.xml}, specifying the name of the target bean in the Spring
 * application context.
 *
 * <p>{@code web.xml} will usually contain a {@code DelegatingFilterProxy} definition,
 * with the specified {@code filter-name} corresponding to a bean name in
 * Spring's root application context. All calls to the filter proxy will then
 * be delegated to that bean in the Spring context, which is required to implement
 * the standard Servlet Filter interface.
 *
 * <p>This approach is particularly useful for Filter implementation with complex
 * setup needs, allowing to apply the full Spring bean definition machinery to
 * Filter instances. Alternatively, consider standard Filter setup in combination
 * with looking up service beans from the Spring root application context.
 *
 * <p><b>NOTE:</b> The lifecycle methods defined by the Servlet Filter interface
 * will by default <i>not</i> be delegated to the target bean, relying on the
 * Spring application context to manage the lifecycle of that bean. Specifying
 * the "targetFilterLifecycle" filter init-param as "true" will enforce invocation
 * of the {@code Filter.init} and {@code Filter.destroy} lifecycle methods
 * on the target bean, letting the servlet container manage the filter lifecycle.
 *

在IOC容器中寻找getTargetBeanName

代码语言:javascript
复制
protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
    Filter delegate = wac.getBean(getTargetBeanName(), Filter.class);
    if (isTargetFilterLifecycle()) {
      delegate.init(getFilterConfig());
    }
    return delegate;
  }

体现在SetFilterBeanName的默认值为filtername

代码语言:javascript
复制
/**
   * Set the name of the target bean in the Spring application context.
   * The target bean must implement the standard Servlet Filter interface.
   * <p>By default, the {@code filter-name} as specified for the
   * DelegatingFilterProxy in {@code web.xml} will be used.
   */
  public void setTargetBeanName(String targetBeanName) {
    this.targetBeanName = targetBeanName;
  }

URL配置采用URL=拦截器【参数】的形式

代码语言:javascript
复制
  /favicon.ico = anon   //过滤器  可以匿名访问
                /logo.png = anon
                /shiro.css = anon
                /s/login = anon
                # allow WebStart to pull the jars for the swing app:
                /*.jar = anon
                # everything else requires authentication:
                /** = authc   //通配符表示认证后才可访问

在实际应用中,使用properties配置通配注解访问,配合MVC达到启用注解并过滤的效果。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-02-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 赵KK日常技术记录 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档