S2SM集成Shiro-登录验证

Struts2+Spring+Mybatis集成Apache Shiro权限控制框架,本章主要讲述如何利用Shiro框架实现登录验证。


扩展Shiro的表单验证过滤器

简述

这里主要用于登录验证失败后,将异常封装成对应的提示消息回写到请求中,方便页面显示验证失败原因。如果不扩展,Shiro会将异常写到请求中(key:shiroLoginFailure),前端jsp页面可以通过shiroLoginFailure键获取取对应的异常信息。

源码-FormAuthenticationFilter.java

package cn.zfcr.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Service;

/** 
    文件名:FormAuthenticationFilter.java
    类说明:  Shiro 表单验证过滤器扩展 写入登录验证失败的错误提示
    作者:章锋
    邮箱: zhangfeng2124@163.com
    日期:2017年6月22日 下午2:29:54  
    描述:例:章锋-认证
    版本:1.0
*/
@Service
public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.FormAuthenticationFilter {
    
    public static final String DEFAULT_MESSAGE_PARAM = "message";
    
    private String messageParam = DEFAULT_MESSAGE_PARAM;

	/**
	 * 登录失败调用事件
	 */
	@Override
	protected boolean onLoginFailure(AuthenticationToken token,
			AuthenticationException e, ServletRequest request, ServletResponse response) {
		String className = e.getClass().getName(), message = "";
		if (IncorrectCredentialsException.class.getName().equals(className)
				|| UnknownAccountException.class.getName().equals(className)){
			message = "用户名或密码错误, 请重试.";
		}
		else if (e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")){
			message = StringUtils.replace(e.getMessage(), "msg:", "");
		}
		else{
			message = "系统异常,请稍后再试!";
			e.printStackTrace();
		}
        request.setAttribute(getFailureKeyAttribute(), className);
        request.setAttribute(getMessageParam(), message);
        return true;
	}
	
	public String getMessageParam() {
        return messageParam;
    }
}


自定义安全认证实现类

简述

安全认证实现类,在这里,主要有两个用途:
1、在登录验证时,根据前端填写的用户名,从数据库中取出对应的用户名密码等信息。
2、访问需要权限验证的url时,从数据中查出当前登录用户的权限。

源码-SystemAuthorizingRealm.java

package cn.zfcr.shiro.realm;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;

import cn.zfcr.base.user.service.UserInfoService;
import cn.zfcr.busi.sysmanage.entity.UserInfo;
import cn.zfcr.common.constants.GlobalConstants;
import cn.zfcr.system.utils.Encodes;

/** 
    文件名:SystemAuthorizingRealm.java
    类说明:  Shiro 安全认证实现类
    作者:章锋
    邮箱: zhangfeng2124@163.com
    日期:2017年6月21日 下午2:29:54  
    描述:例:章锋-认证
    版本:1.0
*/
@Service
public class SystemAuthorizingRealm extends AuthorizingRealm {

	private Logger log = Logger.getLogger(this.getClass().getName());
	
	@Resource
	private UserInfoService userInfoService;

	/**
	 * 认证回调函数, 登录时调用
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
	    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
	    if(log.isDebugEnabled()){
	        log.debug("登录验证:" + token.toString());
	    }
		
		// 校验用户名密码
		UserInfo userInfo = userInfoService.getByLoginName(token.getUsername());
		if (userInfo != null) {
			if (GlobalConstants.NO.equals(userInfo.getLoginFlag())){
				throw new AuthenticationException("该帐号禁止登录.");
			}
			byte[] salt = Encodes.decodeHex(userInfo.getPassword().substring(0,16));
			return new SimpleAuthenticationInfo(new Principal(userInfo), 
					userInfo.getPassword().substring(16), ByteSource.Util.bytes(salt), getName());
		} else {
			return null;
		}
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Principal principal = (Principal) getAvailablePrincipal(principals);
		UserInfo userInfo = userInfoService.getByLoginName(principal.getLoginName());
		if (userInfo != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			
			// 添加用户权限
			info.addStringPermission("user:index");
			
			return info;
		} else {
			return null;
		}
	}
	
	/**
	 * 设定密码校验的Hash算法与迭代次数
	 */
	@PostConstruct
	public void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher("SHA-1");
		matcher.setHashIterations(1024);
		setCredentialsMatcher(matcher);
	}
	
	/**
	 * 授权用户信息
	 */
	public static class Principal implements Serializable {

		private static final long serialVersionUID = 1L;
		
		private String id; // 编号
		private String loginName; // 登录名
		private String name; // 姓名
		private boolean mobileLogin; // 是否手机登录
		
		public Principal(UserInfo user) {
            this.id = user.getId();
            this.loginName = user.getLoginName();
            this.name = user.getName();
        }

		public Principal(UserInfo user, boolean mobileLogin) {
			this.id = user.getId();
			this.loginName = user.getLoginName();
			this.name = user.getName();
			this.mobileLogin = mobileLogin;
		}

		public String getId() {
			return id;
		}

		public String getLoginName() {
			return loginName;
		}

		public String getName() {
			return name;
		}

		public boolean isMobileLogin() {
			return mobileLogin;
		}

		@Override
		public String toString() {
			return id;
		}

	}
}

Shiro配置文件

spring-context-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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
		http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.1.xsd"
	default-lazy-init="true">

	<description>Shiro Configuration</description>

	<!-- Shiro权限过滤过滤器定义 -->
	<bean name="shiroFilterChainDefinitions" class="java.lang.String">
		<constructor-arg>
			<value>
				/common/** = anon
				/css/** = anon
				/framework/** = anon
				/images/** = anon
				/js/** = anon
				
				/login-logout.action = logout
				/login-main.action = authc
				/z/** = user
			</value>
		</constructor-arg>
	</bean>
	
	<!-- 安全认证过滤器 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<property name="securityManager" ref="securityManager" />
		<!-- 跳转到登录页面的action,以及登录表单提交的action(表单必须设置post方式) -->
		<property name="loginUrl" value="/login-main.action" />
		<!-- 登录成功后跳转action,可不配置,默认为/ -->
		<property name="successUrl" value="/" />
		<!-- 自定义过滤器配置 -->
		<property name="filters">
            <map>
                <entry key="cas" value-ref="casFilter"/>
                <entry key="authc" value-ref="formAuthenticationFilter"/>
            </map>
        </property>
        <!-- 过滤器的验证策略配置,指定哪些不需要权限,哪些需要权限,需要什么权限 -->
		<property name="filterChainDefinitions">
			<ref bean="shiroFilterChainDefinitions"/>
		</property>
	</bean>
	
	<!-- CAS认证过滤器 -->  
	<bean id="casFilter" class="org.apache.shiro.cas.CasFilter">  
		<property name="failureUrl" value="/login-main.action"/>
	</bean>
	
	<!-- 定义Shiro安全管理配置 -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="systemAuthorizingRealm" />
		<property name="cacheManager" ref="cacheManager" />
	</bean>
	
	<!-- 缓存配置,如果不配置,shiro不使用缓存 -->
	<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
		<property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
	</bean>
	
	<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
	
	<!-- AOP式方法级权限检查,在方法上指定@RequiresPermissions注解,即可进行权限验证  -->
	<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
		<property name="proxyTargetClass" value="true" />
	</bean>
	<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    	<property name="securityManager" ref="securityManager"/>
	</bean>
	
</beans>

简述

Struts、Spring、Mybatis的配置文件,这里不贴出来了,集成Shiro不需要在这些配置文件中额外添加东西。
http://www.cppblog.com/guojingjia2006/archive/2014/05/14/206956.html,这篇文章中对Shiro的内置过滤器描述的很详细,可以参考下。


Web.xml

添加扫描shiro配置文件
<param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml,classpath:spring-context-shiro.xml</param-value>
<!--     <param-value>classpath:applicationContext.xml</param-value> -->
  </context-param>

指定shiro的过滤器委托给Spring的DelegatingFilterProxy处理
<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>

登录页面的主要代码-main.jsp

        alert('${shiroLoginFailure}');
	alert('${message}');<form id="form1" name="form1" class="login" 
	       autocomplete="off" action="/xxproject/login-main.action" method="post">
	        <p class="title">
                            登录
	        </p>
	        <input type="text" name="username" id="username" placeholder="用户名或邮箱" autofocus/>
	        <i class="fa fa-user">
	        </i>
	        <input type="password" name="password" id="password" placeholder="密码" />
	        <i class="fa fa-key">
	        </i>
	        <a href="#">
	                   忘记密码?
	        </a>
	        <button type="submit" id="btnLogin">
	            <span class="state">
	                            登 录
	            </span>
	        </button>
	    </form>

文本框用户的name必须是username
密码框的name必须是password
必须指定method="post"

测试过程:
输入url进行登录页面,http:/localhost:8080/xxproject/login-main.action
输入错误的用户名,点击登录,此时,应该会弹出UnknownAccountException和用户名或密码错误, 请重试.的提示。
输入正确的用户名和密码,点击登录,此时,应该会跳转到项目主页。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值