1、鉴权处理页通常包括四个方面的设定,分别是鉴权失败、鉴权成功、未鉴权访问、已鉴权但访问了受保护权限。如何自
定义这四类处理。
鉴权失败的默认处理页面是"/spring_security_login?login_error",其默认处理类为SimpleUrlAuthenticationFailureHandler。
鉴权成功的默认处理页面是"/",其默认处理类为SimpleUrlAuthenticationSuccessHandler。
自定义配置如下:
<beans:bean id="authenticationProcessingFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationProcessingFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="authenticationFailureHandler">
<beans:bean class="example.MyAuthenticationFailureHandler">
<beans:property name="defaultFailureUrl" value="/pages/Login/login.do?error=true"/>
</beans:bean>
</beans:property>
<beans:property name="authenticationSuccessHandler">
<beans:bean class="example.MyAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" value="/"/>
</beans:bean>
</beans:property>
</beans:bean>
另外在<http>中增加配置如下:
<custom-filter before="AUTHENTICATION_PROCESSING_FILTER" ref="authenticationProcessingFilter"/>
其中的example.MyAuthenticationFailureHandler和example.MyAuthenticationSuccessHandler为自定义的失败与成功处理类,源码如下:
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler{
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
//增加自己的处理逻辑
super.onAuthenticationFailure(request, response, exception);
}
}
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication auth) throws IOException, ServletException {
//增加自己的处理逻辑
super.onAuthenticationSuccess(request, response, auth);
}
}
未鉴权访问、已鉴权但访问了受保护权限的自定义配置如下:
<beans:bean id="authenticationEntryPoint"
class="example.MyAuthenticationEntryPoint">
<beans:property name="loginFormUrl" value="/login.htm" />
</beans:bean>
<beans:bean id="accessDeniedHandler"
class="example.MyAccessDeniedHandler">
<beans:property name="errorPage" value="/accessDenied.htm" />
</beans:bean>
另外在<http>中增加配置如下:
<http entry-point-ref="authenticationEntryPoint">
<access-denied-handler ref="accessDeniedHandler"/>
</http>
其中的example.MyAuthenticationEntryPoint和example.MyAccessDeniedHandler源码参考如下:
public class MyAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
//增加自己的处理逻辑
super.commence(request, response, authException);
}
}
public class MyAccessDeniedHandler extends AccessDeniedHandlerImpl{
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
throws IOException, ServletException {
//增加自己的处理逻辑
super.handle(request, response, accessDeniedException);
}
}