Java 权限框架 Shiro 实战二:与spring集成、filter机制

深入解析Apache Shiro Web集成:从Filter链到安全实战 在Java Web应用开发中,权限控制与安全管理是构建企业级应用的核心基础。其实现原理通常基于Servlet Filter机制,通过在请求处理链中插入安全过滤器,实现对资源的访问控制。这项技术的核心价值在于提供声明式、非侵入式的安全解决方案,能够有效分离业务逻辑与安全检查代码,提升系统的可维护性和安全性。典型的应用场景包括后台管理系统、金融交易平台、企业内部应用等需要细粒度权限控制的Web项目。本文聚焦于Apache Shiro框架的Web集成机制,深入剖析其Filter链设计、Session管理以及安全配 阅读详情

Shiro和Spring的集成,涉及到很多相关的配置,涉及到shiro的filer机制以及它拥有的各种默认filter,涉及到shiro的权限判断标签,权限注解,涉及到session管理等等方面。

1. 配置

首先需要在web.xml中专门负责接入shiro的filter:

复制代码

    <!-- shiro 安全过滤器 -->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <async-supported>true</async-supported>
        <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中靠前的位置,比如需要放在siteMesh的过滤器之前。

DelegatingFilterProxy 表示这是一个代理filter,它会将实际的工作,交给spring配置文件中 id="shiroFilter" 的bean来处理:

复制代码

public class DelegatingFilterProxy extends GenericFilterBean {
    private String contextAttribute;
    private WebApplicationContext webApplicationContext;
    private String targetBeanName;
    private boolean targetFilterLifecycle = false;
    private volatile Filter delegate;
    private final Object delegateMonitor = new Object();
    @Override
    protected void initFilterBean() throws ServletException {
        synchronized (this.delegateMonitor) {
            if (this.delegate == null) {
                // If no target bean name specified, use filter name.
                if (this.targetBeanName == null) {
                    this.targetBeanName = getFilterName();
                }
                // Fetch Spring root application context and initialize the delegate early,
                // if possible. If the root application context will be started after this
                // filter proxy, we'll have to resort to lazy initialization.
                WebApplicationContext wac = findWebApplicationContext();
                if (wac != null) {
                    this.delegate = initDelegate(wac);
                }
            }
        }
    }

复制代码

复制代码

public abstract class GenericFilterBean implements
        Filter, BeanNameAware, EnvironmentAware, ServletContextAware, InitializingBean, DisposableBean {
    @Override
    public final void init(FilterConfig filterConfig) throws ServletException {
        Assert.notNull(filterConfig, "FilterConfig must not be null");
        if (logger.isDebugEnabled()) {
            logger.debug("Initializing filter '" + filterConfig.getFilterName() + "'");
        }
        this.filterConfig = filterConfig;
        // Set bean properties from init parameters.
        try {
            PropertyValues pvs = new FilterConfigPropertyValues(filterConfig, this.requiredProperties);
            BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
            ResourceLoader resourceLoader = new ServletContextResourceLoader(filterConfig.getServletContext());
            bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.environment));
            initBeanWrapper(bw);
            bw.setPropertyValues(pvs, true);
        }
        catch (BeansException ex) {
            String msg = "Failed to set bean properties on filter '" +
                filterConfig.getFilterName() + "': " + ex.getMessage();
            logger.error(msg, ex);
            throw new NestedServletException(msg, ex);
        }
        // Let subclasses do whatever initialization they like.
        initFilterBean();
        if (logger.isDebugEnabled()) {
            logger.debug("Filter '" + filterConfig.getFilterName() + "' configured successfully");
        }
    }

复制代码

// Let subclasses do whatever initialization they like.

initFilterBean();

Filter 接口的 init 方法调用 initFilterBean(), 而该方法在子类中进行实现,它先获得 this.targetBeanName = getFilterName(); bean的名称,也就是id,然后对其进行初始化:this.delegate = initDelegate(wac); 其实就是从bean工厂中根据bean的名称找到bean.

复制代码

    protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
        Filter delegate = wac.getBean(getTargetBeanName(), Filter.class);
        if (isTargetFilterLifecycle()) {
            delegate.init(getFilterConfig());
        }
        return delegate;
    }

复制代码

而 shiroFilter在spring中的配置如下:

复制代码

    <!-- Shiro的Web过滤器 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/login"/>
        <property name="successUrl" value="/"/>
        <property name="unauthorizedUrl" value="/unauthorized"/>
        <property name="filters">
            <util:map>
                <entry key="authc" value-ref="passThruAuthenticationFilter"/>
            </util:map>
        </property>
        <property name="filterChainDefinitions">
            <value>
                /reg/** = anon    <!-- 注册相关  -->
                /login = authc
                /logout = logout
                /authenticated = authc
                /loginController = anon
                /js/** = anon  
                /css/** = anon   
                /img/** = anon  
                /html/** = anon
                /font-awesome/** = anon  
           <!-- /** = anon 
                /user/modifyPassword = perms["user:update", "user:select"]
           -->
                /** = user
            </value>
        </property>
    </bean>

复制代码

上面的shiroFilter的配置又引出了 securityManager 和 shiro 的filter机制和他自带的一些filter.

2. securityManager 级相关配置

在上一篇文章 Java 权限框架 Shiro 实战一:理论基础 中我们知道securityManager是shiro的顶层对象,它管理和调用其它所有子系统,负责系统的安全。我们知道shiro有两个类型的securityManager:一个是JavaSE环境,默认是DefaultSecurityManager;一个是web环境,默认是DefaultWebSecurityManager。所以我们web环境肯定应该使用后者。我们从顶层对象一层一层向下配置。先看securityManager如何配置:

    <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
        <property name="arguments" ref="securityManager"/>
    </bean>

上面的配置相当于调用SecurityUtils.setSecurityManager(securityManager) ,来注入了下面配置的 securityManager(DefaultWebSecurityManager) :

复制代码

    <!-- 安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="userRealm"/>
        <property name="cacheManager" ref="cacheManager"/>
        <property name="rememberMeManager" ref="rememberMeManager"/>
    </bean>

复制代码

它默认使用的session管理器是 ServletContainerSessionManager,所以上面没有配置,所以就使用默认值。配置了就会覆盖下面的默认值:

复制代码

    public DefaultWebSecurityManager() {
        super();
        ((DefaultSubjectDAO) this.subjectDAO).setSessionStorageEvaluator(new DefaultWebSessionStorageEvaluator());
        this.sessionMode = HTTP_SESSION_MODE;
        setSubjectFactory(new DefaultWebSubjectFactory());
        setRememberMeManager(new CookieRememberMeManager());
        setSessionManager(new ServletContainerSessionManager());
    }

复制代码

显然 securityManager 最重要的工作就是用户登录认证和获得用户的权限等相关信息,所以 realm 是其最重要的依赖:

    <!-- Realm实现 -->
    <bean id="userRealm" class="com.ems.shiro.UserRealm">
        <property name="credentialsMatcher" ref="credentialsMatcher"/>
        <property name="cachingEnabled" value="false"/>
    </bean>

要理解上面userRealm的配置,就的先理解 UserRealm 的继承体系:

UserRealm 继承  AuthorizingRealm 显然是为了获取权限信息,对用户进行访问控制;继承AuthenticatingRealm显然是为了获得用户的认证信息,对用户进行认证。而 credentialsMatcher 就是 AuthenticatingRealm 使用来进行密码验证的依赖的组件:

public abstract class AuthenticatingRealm extends CachingRealm implements Initializable {/**
     * Credentials matcher used to determine if the provided credentials match the credentials stored in the data store.
     */
    private CredentialsMatcher credentialsMatcher;

再看其credentialsMatcher bean的配置:

复制代码

    <!-- 凭证匹配器(验证登录密码是否正确) -->
    <bean id="credentialsMatcher" class="com.ems.shiro.RetryLimitHashedCredentialsMatcher">
        <constructor-arg ref="cacheManager"/>
        <property name="hashAlgorithmName" value="SHA-256"/>
        <property name="hashIterations" value="2"/>
        <property name="storedCredentialsHexEncoded" value="true"/>
    </bean>

复制代码

配置就是 hash加密的相关参数:hash算法,hash迭代次数等。到这里 shiro 登录验证的配置就完了。至于获取用户信息和用户的权限的信息,都在userRealm中实现了:

复制代码

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName = (String)principals.getPrimaryPrincipal();
        User user = userService.getUserByUserName (userName );
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(userService.findRolesByUserId(user.getId()));
        authorizationInfo.setStringPermissions(userService.findPermissionsByUserId(user.getId()));
        return authorizationInfo;
    }    
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String)token.getPrincipal();
        User user = userService.getUserByUserName(userName);
        if(user == null) {
            throw new UnknownAccountException();//没找到账户
        }
        if(user.getLocked() == 0) {
            throw new LockedAccountException(); //帐号锁定
        }
        if(user.getLocked() == 2){
            throw new AuthenticationException("account was inactive");
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user.getUserName(),
                user.getPassword(), // 密码
                ByteSource.Util.bytes(user.getCredentialsSalt()),    // salt
                getName()  // realm name
        );        
        return authenticationInfo;
    }

复制代码

securityManager会在需要的时候回调上面 的 doGetAuthorizationInfo 和 doGetAuthenticationInfo 方法,从realm中获得登录认证信息和用户权限信息。至于 rememberMeManager 主要是实现使用cookie表示我已经登录过了,下次不需要重新登录,这一个功能,也就是“记住我”登录过这一功能:

复制代码

    <!-- rememberMe管理器 -->
    <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
        <!-- rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位)-->
        <property name="cipherKey"
                  value="#{T(org.apache.shiro.codec.Base64).decode('9FvVhtFLUs0KnA3Kprsdyg==')}"/>
        <property name="cookie" ref="rememberMeCookie"/>
    </bean>
    <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg value="rememberMe"/>
        <property name="httpOnly" value="true"/>
        <property name="maxAge" value="2592000"/><!-- 30天 -->
    </bean>

复制代码

还有cacheManager的配置:

复制代码

    <!--ehcache-->
    <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache/ehcache.xml"/>
    </bean>
    <bean id="springCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcacheManager"/>
    </bean>
    <!-- 缓存管理器 -->
    <bean id="cacheManager" class="com.ems.shiro.SpringCacheManagerWrapper">
        <property name="cacheManager" ref="springCacheManager"/>
    </bean>

复制代码

使用的是 EhCache.

3. Shiro 的filter机制和自带的filter

Shiro的filter是基于Servlet的Filter接口实现的。我们通过Shiro提供的form登录filter:FormAuthenticationFilter 和 ShiroFilter 看看其实现:

 

继承中的每一层都实现了一些功能:

1> NameableFilter:实现给filter取名的功能(Allows a filter to be named via JavaBeans-compatible)

复制代码

/**
 * Allows a filter to be named via JavaBeans-compatible*/
public abstract class NameableFilter extends AbstractFilter implements Nameable {
    /**
     * The name of this filter, unique within an application.
     */
    private String name;

复制代码

2> OncePerRequestFilter : 保证对于同一个request,fiter只执行一次(Filter base class that guarantees to be just executed once per request)

/**
 * Filter base class that guarantees to be just executed once per request,
 * on any servlet container. It provides a {@link #doFilterInternal}
 * method with HttpServletRequest and HttpServletResponse arguments.*/
public abstract class OncePerRequestFilter extends NameableFilter {

3> AdviceFilter: SpringMVC风格的过滤器(就是preHandle, postHandle,afterCompletion 三接口的过滤器)

复制代码

 /**
 * A Servlet Filter that enables AOP-style &quot;around&quot; advice for a ServletRequest via
 * preHandle(javax.servlet.ServletRequest, javax.servlet.ServletResponse),
 * postHandle(javax.servlet.ServletRequest, javax.servlet.ServletResponse),
 * and afterCompletion(javax.servlet.ServletRequest, javax.servlet.ServletResponse, Exception)hooks.
 */
public abstract class AdviceFilter extends OncePerRequestFilter {
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        return true;
    }
    @SuppressWarnings({"UnusedDeclaration"})
    protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
    }
    @SuppressWarnings({"UnusedDeclaration"})
    public void afterCompletion(ServletRequest request, ServletResponse response, Exception exception) throws Exception {
    }

复制代码

4> PathMatchingFilter:该过滤器仅仅处理指定的路径(比如上面的配置:/js/** = anon,表示对 /js/ 目录和其子目录的请求,交给anon过滤器处理)

/**
 * <p>Base class for Filters that will process only specified paths and allow all others to pass through.</p>*/
public abstract class PathMatchingFilter extends AdviceFilter implements PathConfigProcessor {

5> AccessControlFilter: 实现提供对资源的访问控制,没有权限时,重定向到登录页面,登录之后跳转到原来的那个页面

复制代码

/**
 * Superclass for any filter that controls access to a resource and may redirect the user to the login page
 * if they are not authenticated.  This superclass provides the method
 * saveRequestAndRedirectToLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
 * which is used by many subclasses as the behavior when a user is unauthenticated.*/
public abstract class AccessControlFilter extends PathMatchingFilter {

复制代码

6> AuthenticationFilter: 实现对访问用户的认证要求,也就是必须登录了才能访问

/**
 * Base class for all Filters that require the current user to be authenticated. This class encapsulates the
 * logic of checking whether a user is already authenticated in the system while subclasses are required to perform
 * specific logic for unauthenticated requests.*/
public abstract class AuthenticationFilter extends AccessControlFilter {

7> AuthenticatingFilter: 实现判断用户是否有权限访问某资源。

/**
 * An AuthenticationFilter that is capable of automatically performing an authentication attempt
 * based on the incoming request.*/
public abstract class AuthenticatingFilter extends AuthenticationFilter {

8> FormAuthenticationFilter:shiro提供的用于实现用户登录功能,如果我们打算自己实现登录,那么我们应用 PassThruAuthenticationFilter 来替代

复制代码

/**
 * Requires the requesting user to be authenticated for the request to continue, and if they are not, forces the user
 * to login via by redirecting them to the setLoginUrl(String) you configure.
 * If you would prefer to handle the authentication validation and login in your own code, consider using the
 * PassThruAuthenticationFilter instead, which allows requests to the loginUrl to pass through to your application's code directly.*/
public class FormAuthenticationFilter extends AuthenticatingFilter {

复制代码

9> PassThruAuthenticationFilter : 用于我们自己在controller中实现登录逻辑时替代FormAuthenticationFilter

复制代码

/**
 * An authentication filter that redirects the user to the login page when they are trying to access
 * a protected resource. However, if the user is trying to access the login page, the filter lets
 * the request pass through to the application code.
 * The difference between this filter and the FormAuthenticationFilter is that
 * on a login submission (by default an HTTP POST to the login URL), the FormAuthenticationFilter filter
 * attempts to automatically authenticate the user by passing the username and password request parameter values to
 * Subject.login(AuthenticationToken) directly.
 * Conversely, this controller always passes all requests to the loginUrl through, both GETs and POSTs.  
 * This is useful in cases where the developer wants to write their own login behavior, which should include a
 * call to Subject.login(AuthenticationToken) at some point.  For example, if the developer has their own custom MVC 
 * login controller or validator, this PassThruAuthenticationFilter may be appropriate.*/
public class PassThruAuthenticationFilter extends AuthenticationFilter {
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            return true;
        } else {
            saveRequestAndRedirectToLogin(request, response);
            return false;
        }
    }
}

复制代码

10> Shiro 自带的filter:

Shiro自身提供了很多的默认filter 来供我们使用,主要分为两种:一是 登录认证相关的filter;一是权限访问控制相关的filter;

登录认证相关的filter有:

1)filter名称: anon, 实现类org.apache.shiro.web.filter.authc.AnonymousFilter,主要用于静态资源的访问,表示无需登录就可以访问;

2)filter名称: authc, 实现类org.apache.shiro.web.filter.authc.FormAuthenticationFilter,主要用于表单登录,没有登录则跳转登录url;

3)filter名称: user, 实现类org.apache.shiro.web.filter.authc.UserFilter,主要用于要求用户已经登录或者通过“记住我”功能登录了也行。

4)filter名称: logout, 实现类org.apache.shiro.web.filter.authc.LogoutFilter,主要用于用户登出

5)filter名称: authcBasic,authc的简化形式,略。

权限访问控制相关的filter有:

1)filter名称: roles, 实现类org.apache.shiro.web.filter.authc.RolesAuthorizationFilter,主要用于验证用户必须拥有某角色,才能继续访问;

2)filter名称: perms, 实现类org.apache.shiro.web.filter.authc.PermissionsAuthorizationFilter,主要用于验证用户必须拥有某权限,才能继续访问;

3)filter名称: ssl, 实现类org.apache.shiro.web.filter.authc.SslFilter,主要用于要求访问协议是https才能访问,不然跳转到https的443短裤;

4)filter名称: port rest noSessionCreation,略。

我们上面的shiroFilter的配置中,已经使用过了上面这些自带的filter:

复制代码

                /reg/** = anon    <!-- 注册相关  -->
                /login = authc
                /logout = logout
                /authenticated = authc
                /loginController = anon
                /js/** = anon  
                /css/** = anon   
                /img/** = anon  
                /html/** = anon
                /font-awesome/** = anon  
                /** = user

复制代码

我们看到 /reg/** 注册相关的,/js/**静态资源都是使用的 anon匿名过滤器,不要求用户已经登录就可以访问。

/** = user 放在最后是要求除了上面那些 url 之外的访问路径,都需要登录认证过或者通过记住我登录认证过。因为路径比较是从上面开始列出来的先开始比较的,匹配了就走该过滤器,不会继续下面的过滤器了。

4. shiro的权限标签

Shiro提供了相应的权限标签,用来实现根据用户的角色和权限来显示它相应的菜单和按钮。首先需要导入shiro标签库:

<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

标签库的定义位于:shiro-web.jar 包中的META-INF/shiro.tld文件中:

 shiro.tld

其中最重要的标签是关于角色和权限的:

<shiro:hasAnyRoles name="student,teacher"></shiro:hasAnyRoles>

<shiro:hasPermission name="user:delete"></shiro:hashPermission>

其它还有关于登录与否的标签:

<shiro:guest></shiro:guest> 未登录可以显示的信息;

<shiro:user></shiro:user> 用户已经登录或者通过记住我登录后显示的信息;

<shiro:authenticated></shiro:authenticated> 必须是实际登录,不是通过记住我登录的

其它标签参考 shiro.tld文件。

shiro标签使用示例:

 View Code

效果是根据用户拥有的角色,来显示左侧有哪些菜单项。

5. shiro 权限注解的使用

shiro对权限的控制,除了前面给出的在 shiroFilter这个bean中配置的过滤器:

复制代码

<property name="filterChainDefinitions">
            <value>
                /reg/** = anon    <!-- 注册相关  -->
                /login = authc
                /logout = logout
                /loginController = anon
                /js/** = anon  
                /css/** = anon   
                /img/** = anon  
                /html/** = anon
                /font-awesome/** = anon  
                /** = user
            </value>
        </property>

复制代码

之外,最重要的就是使用注解的方式来进行访问控制的实现了。shiro权限注解可以达到方法级别的细腻控制,可以控制具有某些权限或者某些角色的用户才能访问某个方法(某个url)。先要开启shiro权限注解功能,开启方法参见文档:http://shiro.apache.org/spring.html

Here is how to enable these annotations. Just add these two bean definitions to applicationContext.xml:

复制代码

<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.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>

复制代码

开启shiro权限注解的方法二:

    <aop:config />
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

<aop:config /> 表示开启spring注解,而 DefaultAdvisorAutoProxyCreator 表示会自动创建代理。但是二者最好不要同时使用。

AuthorizationAttributeSourceAdvisor 通过其依赖的 securityManager 来获取用户的角色和权限信息,进而可以进行权限判断。

支持的shiro注解有:

复制代码

@SuppressWarnings({"unchecked"})
public class AuthorizationAttributeSourceAdvisor extends StaticMethodMatcherPointcutAdvisor {
    private static final Logger log = LoggerFactory.getLogger(AuthorizationAttributeSourceAdvisor.class);
    private static final Class<? extends Annotation>[] AUTHZ_ANNOTATION_CLASSES =
            new Class[] {
                    RequiresPermissions.class, RequiresRoles.class,
                    RequiresUser.class, RequiresGuest.class, RequiresAuthentication.class
            };
    protected SecurityManager securityManager = null;
    public AuthorizationAttributeSourceAdvisor() {
        setAdvice(new AopAllianceAnnotationsAuthorizingMethodInterceptor());
    }

复制代码

RequiresPermissions, RequiresRoles, RequiresUser, RequiresGuest, RequiresAuthentication

主要是通过: AopAllianceAnnotationsAuthorizingMethodInterceptor 类来实现的:

复制代码

public class AopAllianceAnnotationsAuthorizingMethodInterceptor extends AnnotationsAuthorizingMethodInterceptor implements MethodInterceptor{
    public AopAllianceAnnotationsAuthorizingMethodInterceptor() {
        List<AuthorizingAnnotationMethodInterceptor> interceptors = new ArrayList<AuthorizingAnnotationMethodInterceptor>(5);
        //use a Spring-specific Annotation resolver - Spring's AnnotationUtils is nicer than the
        //raw JDK resolution process.
        AnnotationResolver resolver = new SpringAnnotationResolver();
        //we can re-use the same resolver instance - it does not retain state:
        interceptors.add(new RoleAnnotationMethodInterceptor(resolver));
        interceptors.add(new PermissionAnnotationMethodInterceptor(resolver));
        interceptors.add(new AuthenticatedAnnotationMethodInterceptor(resolver));
        interceptors.add(new UserAnnotationMethodInterceptor(resolver));
        interceptors.add(new GuestAnnotationMethodInterceptor(resolver));

        setMethodInterceptors(interceptors);
    }

复制代码

上面注入了注解的拦截器实现。具体的拦截判断权限过程实现如下:

复制代码

public class RoleAnnotationHandler extends AuthorizingAnnotationHandler {
    public RoleAnnotationHandler() {
        super(RequiresRoles.class);
    }
    public void assertAuthorized(Annotation a) throws AuthorizationException {
        if (!(a instanceof RequiresRoles)) return;
        RequiresRoles rrAnnotation = (RequiresRoles) a;
        String[] roles = rrAnnotation.value();
        if (roles.length == 1) {
            getSubject().checkRole(roles[0]);
            return;
        }
        if (Logical.AND.equals(rrAnnotation.logical())) {
            getSubject().checkRoles(Arrays.asList(roles));
            return;
        }
        if (Logical.OR.equals(rrAnnotation.logical())) {
            // Avoid processing exceptions unnecessarily - "delay" throwing the exception by calling hasRole first
            boolean hasAtLeastOneRole = false;
            for (String role : roles) if (getSubject().hasRole(role)) hasAtLeastOneRole = true;
            // Cause the exception if none of the role match, note that the exception message will be a bit misleading
            if (!hasAtLeastOneRole) getSubject().checkRole(roles[0]);
        }
    }
}

复制代码

主要是上面的方法 assertAuthorized(Annotation a) 中来实现对用户是否拥有某些角色进行判断的。其实还是很简单的。

shiro权限注解使用方法如下所示:

复制代码

    @RequiresPermissions(value={"user:update", "user:select"}, logical= Logical.AND)
    @RequestMapping(value="/modifyPassword", method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> modifyPassword(String oldPassword, String newPassword, HttpSession session) {
        Map<String, String> map = new HashMap<>();
        if(oldPassword == null || newPassword == null || newPassword.length() < 8 || newPassword.length() > 32){
            map.put("result", "error");
            map.put("msg", "密码必须在8到20位之间");
            return map;
        }        
        User user = (User)session.getAttribute(ConstantConfig.LONGIN_USER);
        if(user != null){
            PasswordHelper ph = new PasswordHelper();
            if(!ph.checkPasswordAndEncryptPassword(oldPassword, user)){    // 判断输入的 oldPassword是否正确
                map.put("result", "error");
                map.put("msg", "密码错误");
                return map;
            }else{
                user.setPassword(newPassword);
                ph.encryptPassword(user);
                int result = this.userService.updateUserById(user);
                if(result > 0){
                    map.put("result", "ok");
                    map.put("msg", "密码修改成功,请重新登录");
                }else{
                    map.put("result", "error");
                    map.put("msg", "密码修改失败");
                }
                return map;
            }
        }
        return map;
    }

复制代码

@RequiresPermissions(value={"user:update", "user:select"}, logical= Logical.AND)

表示必须有 对 user 表的同时拥有 查询和更新权限,才能修改密码。

分类: Java-shiro

好文要顶 关注我 收藏该文  

digdeep
关注 - 46
粉丝 - 208

+加关注

4

0

« 上一篇:Java 权限框架 Shiro 实战一:理论基础
» 下一篇:Spring AOP 不同配置方式产生的冲突问题

Shiro与Spring Security深度对比及Java Web项目集成实战 在Java Web应用开发中,安全框架是保障系统安全的核心组件。其核心原理是通过认证(Authentication)和授权(Authorization)机制,对用户身份和访问权限进行管控,确保资源访问的合法性。从技术价值看,一个合适的安全框架能有效防御未授权访问、数据泄露等风险,提升系统整体安全性。常见的应用场景包括用户登录、角色权限管理、API接口保护以及微服务架构下的安全治理。本文聚焦于Apache Shiro这一经典框架,通过对比其与Spring Security在设计哲学、功能特性上的核心差异,并结 阅读详情

相关推荐

Apache Shiro与Spring Security终极对比:10个维度解析Java安全框架选型

在Java企业级应用开发中,认证与授权是保障系统安全的基石。认证机制负责验证用户身份,授权模型则控制用户对资源的访问权限,这两者共同构成了应用安全的核心防线。从技术原理上看,安全框架通过封装复杂的加密算法、会话管理和权限验证逻辑,为开发者提供了标准化、可复用的安全解决方案,其技术价值在于显著降低安全功能的实现门槛,提升系统的整体安全水位。在实际工程实践中,不同的安全框架因其设计哲学和架构差异,适用于不同的应用场景:轻量级库更适合快速原型和非Spring技术栈项目,而企业级框架则在微服务架构和OAuth 2.

weixin_30482181的博客 397

shiroFilterFactoryBean that could not be found.

Description: Method filterShiroFilterRegistrationBean in org.apache.shiro.spring.config.web.autoconfigure.ShiroWebFilterConfiguration required a bean named ‘shiroFilterFactoryBean’ that could not be found. Action: Consider defining a bean named ‘shiroFilte

weixin_47617631的博客 2590

Spring Boot、Shiro、SSTI框架漏洞实战:从原理到横向移动

在软件开发领域,框架是提升效率的基石,如Spring Boot、Apache Shiro及各类模板引擎。其核心原理在于通过预置组件和约定,简化通用功能的开发。然而,当框架自身存在安全缺陷时,其广泛部署的特性会将风险急剧放大,形成影响深远的通用攻击面。这类漏洞的技术价值在于,攻击者无需针对每个定制应用,掌握针对框架的通用攻击手法即可实现批量突破,极大提升了攻击效率。典型的应用场景包括未授权访问、反序列化漏洞和服务器端模板注入(SSTI)。例如,Spring Boot Actuator的配置不当可导致敏感信息泄

liudaoru - 悟 472

shiro(二):springboot整合shiro

/自定义realm public class CustomRealm1 extends AuthorizingRealm {//从传过来的token获取到的用户名 String principal =(String) token . getPrincipal();System . out . println("用户名" + principal);//假设是从数据库获得的 用户名,密码 String password_db = "123";} }

weixin_39724194的博客 1199

Shiro框架中SecurityManager丢失的排查与修复指南

在Java Web应用开发中,权限控制是保障系统安全的核心环节。Apache Shiro作为轻量级安全框架,通过SecurityManager统一管理认证、授权等安全事务,其底层依赖ThreadLocal机制实现线程绑定的上下文管理。当应用执行权限检查或登录验证时,若无法从当前线程上下文中获取SecurityManager实例,将导致安全操作中断,影响系统功能完整性。这一机制在Web请求处理、异步任务执行等场景中尤为重要,直接关系到权限体系的稳定运行。针对Shiro框架中常见的“No SecurityMan

weixin_30698527的博客 462

Java安全框架选型:Spring Security、Shiro与Sa-Token对比

权限管理是系统安全的核心环节,涉及认证、授权、会话管理和安全防护等关键技术。在Java生态中,Spring Security以其企业级特性著称,提供完善的OAuth2支持和深度Spring集成;Apache Shiro则以轻量灵活见长,适合快速实现RBAC模型;新兴的Sa-Token凭借无Cookie设计和分布式会话支持,在微服务场景表现突出。本文从架构设计、学习曲线、性能指标等维度,对比三大框架在认证授权、CSRF防护、分布式会话等核心功能的实现差异,并结合OAuth2、JWT等热词技术,为不同规模项目提

weixin_33682790的博客 433

解决spring boot shiro的 Consider defining a bean named ‘shiroFilterFactoryBean‘ in your configuration问题

解决spring boot配置shiro的 Consider defining a bean named 'shiroFilterFactoryBean' in your configuration问题。

念兮为美 2493

k8s重装1.28.2+calico+踩坑收集+InPlacePodVerticalScaling

它提供了从镜像构建(通过 Dockerfile)、镜像管理(上传、下载、存储等)、容器创建、运行、网络配置(可以为容器分配自定义的网络,如 bridge 网络、host 网络等)到容器编排(通过 Docker Compose 可以简单地编排多个容器的启动和关联关系)等一整套完整的解决方案。它的核心功能是启动和管理容器的生命周期。sudo apt update这个可以经常用,是来更新软件包的,它不下载,所以没风险,但是经常会报错,别问,问就是某种强大的力量,所以用镜像或者代理或者巴拉巴拉。

SsjjsS2019的博客 2555

Springboot2(23)轻松整合shiro(带验证码)

源码地址 springboot2教程系列 Shiro配置 1.Spring集成Shiro一般通过xml配置,SpringBoot集成Shiro一般通过java代码配合@Configuration和@Bean配置。 2.Shiro的核心通过过滤器Filter实现。Shiro中的Filter是通过URL规则来进行过滤和权限校验,所以我们需要定义一系列关于URL的规则和访问权限。 3.SpringB...

cowbin2012的专栏 2万+

grafana使用方法

1、点击仪表盘2、新建仪表盘3、选择数据源4、选择查询的条件5、美化。

2403_87359664的博客 326

基于PID算法的循迹小车

这一期为创客们带来基于PID算法的循迹小车制作 1.标准赛道示意图: (该赛道包含了:左直角、右直角、十字路口等路况) 2.灰度传感器安装示意图: (可根据实际情况调节各传感器之间的间距) 3.硬件原理图: 4.控制逻辑: 5.程序如下: #define leftA_PIN 7 #define leftB_PIN 6 #define left_Pwm_PIN 5 #define STBY...

qq_44343584的博客 4万+

Shiro | 实现权限验证完整版

写在前面的话 提及权限,就会想到安全,是一个十分棘手的话题。这里只是作为学校Shiro的一个记录,而不是,权限就应该这样设计之类的。 Shiro框架 1、Shiro是基于Apache开源的强大灵活的开源安全框架。 2、Shiro提供了 认证,授权,企业会话管理、安全加密、缓存管理。 3、Shiro与Security对比 4、Shiro整体架构 5、特性 6、认证流程 认证 当我们理解Shi...

冯文议技术博客 8096

手把手教你用PlantVillage数据集搭建农作物病害识别模型(Python实战)

本文详细介绍了如何使用PlantVillage数据集和Python构建农作物病害识别模型。从环境准备、数据获取到模型构建、训练与评估,手把手教你实现一个实用的农业AI应用。特别针对PlantVillage数据集的特点,提供了处理类别不平衡、图像预处理和模型优化的实战技巧,帮助开发者快速掌握农作物病害识别技术。

weixin_29184371的博客 481

Java 权限框架 Shiro 实战二:与spring集成、filter机制,shirofilter

Shiro和Spring的集成,涉及到很多相关的配置,涉及到shiro的filer机制以及它拥有的各种默认filter,涉及到shiro的权限判断标签,权限注解,涉及到session管理等等方面。 1. 配置 首先需要在web.xml中专门负责接入shiro的filter: shiro 安全过滤器 --> filter> filter-name>shiroF

ntc10095的博客 1280

SQL的基本介绍

1.什么是数据库?2.什么是数据库管理系统?3.什么是 SQL?1.数据库是保存有组织的数据的容器,通常是一个文件或一组文件,可以将其看作电子化的文件柜。用户可以对文件中的数据执行新增、删除、更新、查询等操作。2.数据库管理系统是一种操纵和管理数据库的大型软件,用于建立、使用和维护数据库,简称DBMS。它对数据库进行统一的管理和控制,以保证数据库的安全性和完整性。用户可以通过 DBMS 访问数据库中的数据,数据库管理员也可以通过 DBMS 进行数据库的维护工作。

shiwei0813的博客 2879

仿真学习系列(三十八):Sigrity仿真之单端S参数提取

S 参数(Scattering Parameters)是高速信号分析中最基础也最常用的指标,能够全面表征走线、过孔、连接器等互连结构的高频行为。在 Sigrity PowerSI 中,Model Extraction 是最常用的 S 参数提取方式,适用于高速差分线、单端线、过孔、参考平面等各种拓扑结构。 本节将通过示例讲解如何在 PowerSI 中完成一次完整的 S 参数提取流程,包括:对象选择、端口设置、频率范围配置以及结果查看。掌握此方法后,即可对任意高速网络执行阻抗、插损、回损、串扰分析,为进一步的

案例文章,高速信号 838

Spring Boot整合Apache Shiro权限认证框架(基础篇)

本文详细介绍了在SpringBoot项目中整合Apache Shiro实现认证和授权的完整流程。主要内容包括:1)创建SpringBoot项目并添加Shiro依赖;2)配置数据库和用户表;3)实现公共响应类和异常处理;4)创建Shiro核心组件(Realm、配置类);5)实现登录认证功能;6)通过权限控制实现接口访问限制。文章提供了完整的代码示例,包括前端页面交互和后端接口实现,并演示了权限验证效果。通过本文可以快速掌握Shiro在SpringBoot中的基本应用,为项目添加安全控制层。

沐雨橙风ιε的博客 1万+

ROSTCM6软件下载及语义网络分析详细操作教程(附网盘链接)

ROSTCM6是武汉大学沈阳教授研发编码的国内目前唯一的以辅助人文社会科学研究的大型免费社会计算平台。该软件可以实现微博分析、聊天分析、全网分析、网站分析、浏览分析、分词、词频统计、英文词频统计、流量分析、聚类分析等一系列文本分析。

m0_64336780的博客 4万+

Spring Boot 安全框架 Shiro 与 Security 全面解析​

Spring Boot安全框架对比:Shiro与Spring Security解析 本文对比了Spring Boot中两种主流安全框架:Apache Shiro和Spring Security。从架构上看,Shiro采用"三大核心+四大辅助"的简洁设计,而Spring Security基于过滤器链实现。Shiro优势在于简单易用、跨平台性强,适合中小项目;Spring Security深度集成Spring生态,功能全面,更适合企业级应用。文章详细分析了两者的适用场景:Shiro适用于We

深耕 Java 后端与企业级软件架构设计,专注微服务、分布式系统、大模型 AI 应用架构落地。 1441

第十七章:载板成本结构分析

本文分析了ABF和BT载板的成本结构,其中ABF载板材料成本占比50%(主要来自ABF薄膜),制造成本35%,利润15%;BT载板材料成本45%,制造成本40%。ABF薄膜价格预计将从2023年的80-90美元/panel上涨至2026年的120-150美元。良率每提升1%可降低成本约5%,产能利用率每提高10%可降本3-5%。通过设计优化(如减少层数)、工艺改进(提升良率)和供应链优化(材料国产化)可有效降低成本。预计2024-2028年AI用ABF载板成本将上涨10-15%,而手机用BT载板涨幅约5%。

Open 317

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Servlet与SpringBoot与shiro的鉴权机制

Servlet与SpringBoot与shiro的鉴权机制

没有网络安全就没有国家安全 930

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

上一篇: 发一份shiro标准配置,特此记录
下一篇: 在 Web 项目中应用 Apache Shiro 并集成 CAS 单点登录
王树民
博客等级 码龄10年 912粉丝 560原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值