网站认证和授权(自定义权限)

序言

Shrio是java的一个权限框架,可以完成认证、授权、加密、会话管理、集成Web、缓存等。Shiro可以应用在JavaSE中,也可以应用在JavaEE中,这里主要学习Shiro与Web整合,实现网站权限管理。

SSM整合Shiro

SSM整合Shiro(这里对SSM的整合不再详细说明,具体可以看 SSM框架整合)需要导入4个jar包,分别为:shiro-all,log4j,slf4j-api,slf4j-log4j12。同时也需要缓存的核心包:ehcache-core,之后配置shiro的过滤器,在web.xml中添加如下代码:
web.xml
<!-- 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>
同时在spring的配置文件中加载shiro的相关配置,在classpath目录下加入缓存的配置文件ehcache.xml,内容都有详细的注释,这里就不再做多的说明,具体实现如下:
applicaitonContext.xml
<!--shiro相关配置-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <property name="cacheManager" ref="cacheManager"/>
    <property name="realms" ref="jdbcRealm"></property>
</bean>
<!--加载ehcache.xml缓存文件-->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
    <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>
<!-- 配置自定义的realm,对传入的密码采用MD5加密,下文会再说明 -->
<bean id="jdbcRealm" class="com.tms.shiro.ShiroRealm">
    <property name="credentialsMatcher">
        <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
            <property name="hashAlgorithmName" value="MD5"></property>
        </bean>
    </property>
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- 启动IOC容器中使用shiro的注解 -->
<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会自动清除缓存 -->
<bean id="logout" class="org.apache.shiro.web.filter.authc.LogoutFilter">
    <property name="redirectUrl" value="/admin/login.html"/>
</bean>
<!--ShiroFilter,unauthorizedUrl:没权限时跳转的路径 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"/>
    <property name="loginUrl" value="/admin/login.html"/>
    <property name="successUrl" value="/admin/index.html"/>
    <property name="unauthorizedUrl" value="/admin/limit.html"/>
    <property name="filterChainDefinitions">
        <value>
	    <!-- anon表示不拦截的路径 -->
            /admin/login.html = anon
            /admin/css/** = anon
            /admin/js/** = anon
	    <!-- authc表示拦截的路径 -->
            /admin/** = authc
	    <!-- logout表示登出 -->
            /admin/logout.html = logout
        </value>
    </property>
</bean>
ehcache.xml
<ehcache>
    <diskStore path="java.io.tmpdir"/>
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU" />
</ehcache>
自定义的ShiroRealm(核心)
想要实现认证和授权,可以通过自定义Realm继承AuthorizingRealm实现,同时实现doGetAuthenticationInfo(认证)和doGetAuthorizationInfo(授权),具体实现如下:
public class ShiroRealm extends AuthorizingRealm{
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        String account = userToken.getUsername();
        Admin admin = adminMapper.selectByAccount(account);
        if(admin==null){
            throw  new UnknownAccountException("用户不存在");
        }
        String password = admin.getPassword();
        String realmName = getName();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(account,password,realmName);
        return info;
    }
    //授权,懒加载,访问用户是否有权限是才执行该方法,一次执行后便存在缓存里,下次访问则直接从缓存中访问
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	//获取登录用户
        String account = principals.getPrimaryPrincipal().toString();
        Set<String> roles = new HashSet<>();
	//数据库里查询用户的权限
        Authority authority = authorityMapper.selectByAccount(account);        
	//判断是否拥有权限,有便授权
	if(authority.getAdvertise()){            
		roles.add("advertise");        
	}        
	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);        
	return info;    
    }
}

Controller

//调用Shiro的方法SecurityUtils.getSubject()返回当前访问的对象
Subject user = SecurityUtils.getSubject();
//判断当前用户没被认证
if (!user.isAuthenticated()) {
    String account = request.getParameter("account");
    String password = request.getParameter("password");
    UsernamePasswordToken token = new UsernamePasswordToken(account, password);
    token.setRememberMe(true);
    try {
	//会去访问自定义Realm的认证方法
        user.login(token);
    }
    catch (AuthenticationException e) {
	//这里直接捕获AuthenticationException异常,账号错误,不存在,密码错误均会抛出异常
    }
}

结尾再说一下

至此便实现了一个简单的Shiro认证和授权的功能,Shiro可以通过标签实现对页面的控制,例如:<shiro:hasRole name="权限名"></shiro:hasRole>在页面中判断当前用户是否具有该权限,<shiro:principal/>显示当前认证的账号,当然,使用之前需要引入标签库(<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>)。至于shiro实现的源代码和机制,可以访问shiro官网下载shiro的源码学习了解。

猜你喜欢

转载自blog.csdn.net/hsf15768615284/article/details/77828421