shiro权限 的基本配置

1.编写一个自定义权限类(继承AuthorizingRealm )

package com.zking.test.shiro;

import com.zking.test.biz.IUserBiz;
import com.zking.test.model.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Set;

/**
 * 自定义Realm
 */
public class UserRealm extends AuthorizingRealm {

    private static final Integer LOCKED = new Integer(1);

    //用户对应的角色信息与权限信息都保存在数据库中,通过IUserBiz获取数据
    private IUserBiz userBiz;

    public UserRealm() {

    }

    public UserRealm(CacheManager cacheManager) {
        super(cacheManager);
    }

    public UserRealm(CredentialsMatcher matcher) {
        super(matcher);
    }

    public UserRealm(CacheManager cacheManager, CredentialsMatcher matcher) {
        super(cacheManager, matcher);
    }

    public void setUserBiz(IUserBiz userBiz) {
        this.userBiz = userBiz;
    }

    /**
     * 返回一个唯一的Realm名字
     *
     * @return
     */
    @Override
    public String getName() {
        return "UserRealm";//WeixinRealm,QqRealm,WeixinQqRealm
    }

    /**
     * 判断此Realm是否支持此Token
     *
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;//仅支持UsernamePasswordToken类型的Token
    }

    /**
     * 提供用户信息返回授权信息
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //查询用户已授予的角色及权限
        String username = (String) principalCollection.getPrimaryPrincipal();
        User user = new User();
        user.setUsername(username);
        Set<String> permissions = userBiz.listPermissionsByUserName(user);
        Set<String> roles = userBiz.listRolesByUserName(user);

        //返回授权信息
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);//
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    /**
     * 提供用户信息返回认证信息(此时未进行密码比较)
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //查询用户已授予的角色及权限
        String username = (String) authenticationToken.getPrincipal();
        User user = new User();
        user.setUsername(username);
        User u = userBiz.loadByUsername(user);

        if (null == u) {
            throw new UnknownAccountException();//帐号不存在
        }
        if (LOCKED.equals(u.getLocked())) {
            throw new LockedAccountException(); //帐号已锁定
        }

        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以在此判断或自定义实现
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                u.getUsername(),
                u.getPassword(),
                ByteSource.Util.bytes(u.getSalt()),
                getName()
        );
        return authenticationInfo;
    }
}

2 编写一个凭证匹配器类

package com.zking.test.shiro;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 提供了不允许连续错误登录的判断。真正匹配的过程还是交给它的直接父类去完成。
 * 连续登录错误的判断依靠Ehcache缓存来实现。显然match返回true为匹配成功
 */
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {

    // 声明一个缓存接口,这个接口是Shiro缓存管理的一部分,它的具体实现可以通过外部容器注入
    private Cache<String, AtomicInteger> passwordRetryCache;

    //使用的缓存对象的名字
    private String cacheName = "passwordRetryCache";

    //缓存管理器
    private CacheManager cacheManager;

    public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    public void setCacheName(String cacheName) {
        this.cacheName = cacheName;
    }

    public void init() {
        passwordRetryCache = cacheManager.getCache(this.cacheName);
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String username = (String) token.getPrincipal();
        AtomicInteger retryCount = passwordRetryCache.get(username);
        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }
        // 自定义一个验证过程:当用户60秒内连续输入密码错误5次以上禁止用户登录一段时间(60秒时间是在ehcache.xml中设置的)
        if (retryCount.incrementAndGet() > 5) {
            throw new ExcessiveAttemptsException();
        }
        boolean match = super.doCredentialsMatch(token, info);
        if (match) {
            passwordRetryCache.remove(username);
        }
        return match;
    }
}

3 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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    <description>apache shiro配置</description>

    <!-- 缓存管理器:本章使用Ehcache实现,也可以换成redis等其它缓存技术 -->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
    </bean>

    <!-- 凭证匹配器 -->
    <bean id="credentialsMatcher" class="com.zking.test.shiro.RetryLimitHashedCredentialsMatcher" init-method="init">
        <!--使用有参数构造方法创建对象,注入缓存管理器-->
        <constructor-arg ref="cacheManager"/>

        <!--指定缓存对象的名字-->
        <property name="cacheName" value="passwordRetryCache"/>

        <!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
        <!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
        <!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
        <!--以下三个配置告诉shiro将如何对用户传来的明文密码进行加密-->
        <!--指定hash算法为MD5-->
        <property name="hashAlgorithmName" value="md5"/>
        <!--指定散列次数为1024-->
        <property name="hashIterations" value="1024"/>
        <!--true指定Hash散列值使用Hex加密存. false表明hash散列值用用Base64-encoded存储-->
        <property name="storedCredentialsHexEncoded" value="true"/>
    </bean>

    <!-- Realm实现 配置一个自定义权限类 -->
    <bean id="userRealm" class="com.zking.test.shiro.UserRealm">
        <property name="credentialsMatcher" ref="credentialsMatcher"/>
        <property name="userBiz" ref="userBiz"/>
    </bean>

    <!-- 配置安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">

        <property name="realm" ref="userRealm"/>
    </bean>

    <!-- 配置Shiro的Web过滤器 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <!--访问需要认证的地址时,没有认证跳转的地址,默认跳网站首页,然后经springmvc转到/WEB-INF/jsp/login.jsp-->
        <property name="loginUrl" value="/"/>

        <!-- 登录后,没有访问权限将跳转的地址 -->
        <property name="unauthorizedUrl" value="/user/unauthorized"/>

        <property name="filterChainDefinitions">
            <!-- **表示匹配0个或多个路径 ,*表示匹配0个或多个字符串,?表示匹配一个字符 -->
			<!-权限列表-->
            <value>
                /css/**               = anon
                /images/**            = anon
                /js/**                = anon
                /                     = anon
                /user/logout          = logout
                /user/**              = anon
                /userInfo/**          = authc
                /dict/**              = authc
                /console/**           = roles[admin]
                /sys/**               = authc
                /**                   = anon
            </value>
        </property>
    </bean>

    <!-- Shiro生命周期处理器-->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

</beans>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值