Shiro教程、验证码kaptcha、successUrl不跳转问题解决

shiro教程 http://jinnianshilongnian.iteye.com/blog/2018398
验证码kaptcha http://aperise.iteye.com/blog/2276496

FormAuthenticationFilter

的successUrl不跳转问题

http://aperise.iteye.com/blog/2276496

1.shiro教程

  shiro教程参见这篇博客,讲解的太细了,也讲的非常到位,望尘莫及,膜拜膜拜!

  《跟我学Shiro》教程   http://jinnianshilongnian.iteye.com/blog/2018398

第一章  Shiro简介 http://jinnianshilongnian.iteye.com/blog/2018936
第二章  身份验证 http://jinnianshilongnian.iteye.com/blog/2019547
第三章  授权 http://jinnianshilongnian.iteye.com/blog/2020017
第四章  INI配置 http://jinnianshilongnian.iteye.com/blog/2020820
第五章  编码/加密 http://jinnianshilongnian.iteye.com/blog/2021439
第六章  Realm及相关对象 http://jinnianshilongnian.iteye.com/blog/2022468
第七章  与Web集成 http://jinnianshilongnian.iteye.com/blog/2024723
第八章 拦截器机制 http://jinnianshilongnian.iteye.com/blog/2025656
第九章 JSP标签 http://jinnianshilongnian.iteye.com/blog/2026398
第十章  会话管理 http://jinnianshilongnian.iteye.com/blog/2028675
第十一章  缓存机制 http://jinnianshilongnian.iteye.com/blog/2029217
第十二章  与Spring集成 http://jinnianshilongnian.iteye.com/blog/2029717
第十三章  RememberMe http://jinnianshilongnian.iteye.com/blog/2031823
第十四章  SSL http://jinnianshilongnian.iteye.com/blog/2036420
第十五章  单点登录 http://jinnianshilongnian.iteye.com/blog/2036730
第十六章  综合实例 http://jinnianshilongnian.iteye.com/blog/2037222
第十七章  OAuth2集成 http://jinnianshilongnian.iteye.com/blog/2038646
第十八章 并发登录人数控制 http://jinnianshilongnian.iteye.com/blog/2039760
第十九章 动态URL权限控制 http://jinnianshilongnian.iteye.com/blog/2040929
第二十章 无状态Web应用集成 http://jinnianshilongnian.iteye.com/blog/2041909
第二十一章 授予身份及切换身份 http://jinnianshilongnian.iteye.com/blog/2044616
第二十二章 集成验证码 http://jinnianshilongnian.iteye.com/blog/2046041
第二十三章 多项目集中权限管理及分布式会话 http://jinnianshilongnian.iteye.com/blog/2047168
第二十四章 在线会话管理 http://jinnianshilongnian.iteye.com/blog/2047643

2.shiro中增加验证码kaptcha

  2.1 增加对于kaptcha的maven依赖

		<!-- kaptcha验证码 -->
		<dependency>
			<version>0.0.9</version>
			<groupId>com.github.axet</groupId>
			<artifactId>kaptcha</artifactId>
		</dependency>
 

  2.2 web.xml中增加kaptcha servlet拦截

	<!-- kaptcha验证码 -->
	<servlet>
		<servlet-name>kaptcha</servlet-name>
		<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
		<init-param>
			<param-name>kaptcha.noise.impl</param-name>
			<param-value>com.google.code.kaptcha.impl.NoNoise</param-value>
		</init-param>
		<!-- 验证码图片是否有边框 -->
		<init-param>
			<param-name>kaptcha.border</param-name>
			<param-value>yes</param-value>
		</init-param>
		<!-- 验证码图片宽度 -->
		<init-param>
			<param-name>kaptcha.image.width</param-name>
			<param-value>100</param-value>
		</init-param>
		<!-- 验证码图片高度 -->
		<init-param>
			<param-name>kaptcha.image.height</param-name>
			<param-value>50</param-value>
		</init-param>
		<!-- 图片上验证码位数 -->
		<init-param>
			<param-name>kaptcha.textproducer.char.length</param-name>
			<param-value>4</param-value>
		</init-param>
	</servlet>
	<!-- 拦截request路径为/kaptcha.jpg的请求,然后调用kaptcha产生验证码 -->
	<servlet-mapping>
		<servlet-name>kaptcha</servlet-name>
		<url-pattern>/kaptcha.jpg</url-pattern>
	</servlet-mapping>
 

  2.3 login.jsp页面增加验证码功能

<script type="text/javascript">
var captcha;
function refreshCaptcha(){  
    document.getElementById("img_kaptcha").src="${contextPath}/kaptcha.jpg?t=" + Math.random();  
} 
</script>
	<li>
		<label for="username">用户名:</label>
		<input type="text" name="username" class="login_input" id="username" />
	</li>
	<li>
		<label for="password">密码:</label>
		<input type="password" name="password" class="login_input" id="password" autocomplete="off" />
	</li>
	<li>
 		<label for="kaptcha">验证码:</label>
		<input type="text" name="kaptcha"  class="login_input_kaptcha" id="kaptcha" autocomplete="off" />
		<img   class="login_input_kaptcha_img" alt="验证码" src="${contextPath}/kaptcha.jpg" title="点击更换" id="img_kaptcha"  onclick="javascript:refreshCaptcha();" />
	</li>
 

  2.4 shiro配置里实现一个自己的AccessControlFilter类KaptchaFilter

public class KaptchaFilter extends AccessControlFilter {
	private String kaptchaParam = "kaptcha";// 前台提交的验证码参数名

	public String getKaptchaParam() {
		return kaptchaParam;
	}

	public void setKaptchaParam(String kaptchaParam) {
		this.kaptchaParam = kaptchaParam;
	}

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
		// 验证验证码是否正确
		if (null == request.getParameter(kaptchaParam)) {
			return true;
		} else {
			String kaptchaFromWeb = (String) request.getParameter(kaptchaParam);
			String kaptchaFromSession = (String) httpServletRequest.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
			return kaptchaFromSession.toUpperCase().equals(kaptchaFromWeb.toUpperCase());
		}
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		// 如果验证码失败了,存储失败key属性
		request.setAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, "Kaptcha.error");
		return true;
	}
}
 

  2.5 重写自己的FormAuthenticationFilter为KaptchaFormAuthenticationFilter

public class KaptchaFormAuthenticationFilter extends FormAuthenticationFilter {
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		if (request.getAttribute(getFailureKeyAttribute()) != null) {
			return true;
		}
		return super.onAccessDenied(request, response, mappedValue);
	}

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,ServletResponse response) throws Exception {
		WebUtils.issueRedirect(request, response, getSuccessUrl());
		return false;
	}
}
 

  2.6 shiro配置里修改如下

	<!-- 基于Form表单的身份验证过滤器 -->
	<bean id="formAuthenticationFilter" class="com.xxx.shrio.filter.KaptchaFormAuthenticationFilter">
		<property name="usernameParam" value="username" />
		<property name="passwordParam" value="password" />
		<property name="rememberMeParam" value="rememberMe" />
		<property name="loginUrl" value="/login" />
        <property name="successUrl" value="/index"/>
	</bean>
<bean id="kaptchaFilter" class="com.xxx.shrio.filter.KaptchaFilter">
		<property name="kaptchaParam" value="kaptcha" />
	</bean>  

    <!-- 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="/index"/>
        <property name="unauthorizedUrl" value="/redirect"/>
        <property name="filters">
            <util:map>
				<entry key="authc" value-ref="formAuthenticationFilter" />
				<entry key="sysUser" value-ref="sysUserFilter" />
				<entry key="kaptcha" value-ref="kaptchaFilter" />
            </util:map>
        </property>
        <property name="filterChainDefinitions">
            <value>
            	/login = kaptcha,authc
            	/unauthorized.jsp = authc
            	/redirect = anon
            	/css/** = anon
            	/js/** = anon
            	/img/** = anon
            	/kaptcha.jpg = anon
            	/** = user,sysUser
            </value>
        </property>
    </bean>
 

  2.7 最后验证码添加后效果


 

3.shiro的FormAuthenticationFilter的successUrl不跳转问题

  3.1 首先查看shiro源代码WebUtils类里方法

/**
     * Redirects the to the request url from a previously
     * {@link #saveRequest(javax.servlet.ServletRequest) saved} request, or if there is no saved request, redirects the
     * end user to the specified {@code fallbackUrl}.  If there is no saved request or fallback url, this method
     * throws an {@link IllegalStateException}.
     * <p/>
     * This method is primarily used to support a common login scenario - if an unauthenticated user accesses a
     * page that requires authentication, it is expected that request is
     * {@link #saveRequest(javax.servlet.ServletRequest) saved} first and then redirected to the login page. Then,
     * after a successful login, this method can be called to redirect them back to their originally requested URL, a
     * nice usability feature.
     *
     * @param request     the incoming request
     * @param response    the outgoing response
     * @param fallbackUrl the fallback url to redirect to if there is no saved request available.
     * @throws IllegalStateException if there is no saved request and the {@code fallbackUrl} is {@code null}.
     * @throws IOException           if there is an error redirecting
     * @since 1.0
     */
    public static void redirectToSavedRequest(ServletRequest request, ServletResponse response, String fallbackUrl)
            throws IOException {
        String successUrl = null;
        boolean contextRelative = true;
        SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);
        if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) {
            successUrl = savedRequest.getRequestUrl();
            contextRelative = false;
        }

        if (successUrl == null) {
            successUrl = fallbackUrl;
        }

        if (successUrl == null) {
            throw new IllegalStateException("Success URL not available via saved request or via the " +
                    "successUrlFallback method parameter. One of these must be non-null for " +
                    "issueSuccessRedirect() to work.");
        }

        WebUtils.issueRedirect(request, response, successUrl, null, contextRelative);
    }
     首先通过SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);

从session中获取到第一次请求时的地址,然后通过successUrl = savedRequest.getRequestUrl();

将FormAuthenticationFilter配置的successUrl值覆盖掉所以shiro默认跳转到了首次请求的url了。

  3.2 shiro的FormAuthenticationFilter的successUrl不跳转问题解决

    重写自己的FormAuthenticationFilter类KaptchaFormAuthenticationFilter,主要是覆盖里面的方法onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,ServletResponse response),代码如下:

public class KaptchaFormAuthenticationFilter extends FormAuthenticationFilter {
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		if (request.getAttribute(getFailureKeyAttribute()) != null) {
			return true;
		}
		return super.onAccessDenied(request, response, mappedValue);
	}

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,ServletResponse response) throws Exception {
		WebUtils.issueRedirect(request, response, getSuccessUrl());
		return false;
	}
}
    然后覆盖shiro配置:
	<!-- 基于Form表单的身份验证过滤器 -->
	<bean id="formAuthenticationFilter" class="com.xxx.shrio.filter.KaptchaFormAuthenticationFilter">
		<property name="usernameParam" value="username" />
		<property name="passwordParam" value="password" />
		<property name="rememberMeParam" value="rememberMe" />
		<property name="loginUrl" value="/login" />
        <property name="successUrl" value="/index"/>
	</bean>
    这样, shiro登录成功后只会跳转到FormAuthenticationFilter配置的successUrl这个地址。 4.shiro集成spring 4.x和quartz 2.x报错java.lang.InstantiationError: org.quartz.SimpleTrigger      shiro集成spring 4.x和quartz 2.x报错java.lang.InstantiationError: org.quartz.SimpleTrigger,主要原因是shiro的org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler是对quartz1.x的实现,但是quartz2.x已经变动很大,导致整合quartz2.x时候,shiro原来对于shiro的实现不可用 ,解决办法如下:     4.1 自己实现quartz2.x的 org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler     shiro对于quartz1.x的实现如下:     现在自己更改这个实现如下:      4.2 更改配置为自己的实现  

猜你喜欢

转载自aperise.iteye.com/blog/2276496
今日推荐