Spring Security 4.X xml配置重定向
阿新 • • 發佈:2019-02-02
<!-- 後臺許可權控制 @PreAuthorize --> <global-method-security pre-post-annotations="enabled" />
<form-login login-page="/login" authentication-success-handler-ref="successHandler" authentication-failure-url="/login?error=1" authentication-success-forward-url="/main.to" />
<http use-expressions="false" > ... <expression-handler ref="webexpressionHandler" ></expression-handler> </http>
<!--配置web端使用許可權控制--> <beans:bean id="webexpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" />
<!-- 重定向 /login?redirect= 重定向url --><beans:bean id="successHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"> <beans:property name="targetUrlParameter" value="redirect"></beans:property> <beans:property name="redirectStrategy"> <beans:bean class="com.framework.redirect.MyRedirectStrategy"></beans:bean> </beans:property> </beans:bean>
package com.framework.redirect; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.util.UrlUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class MyRedirectStrategy extends DefaultRedirectStrategy { @Override public void sendRedirect(final HttpServletRequest request, final HttpServletResponse response, final String url) throws IOException { String redirectUrl = calculateRedirectUrl(request.getContextPath(), url); redirectUrl = response.encodeRedirectURL(redirectUrl); if (logger.isDebugEnabled()) { logger.debug("Redirecting to '{"+redirectUrl+"}'"); } response.sendRedirect(redirectUrl); } private String calculateRedirectUrl(String contextPath, String url) { if (!UrlUtils.isAbsoluteUrl(url)){ return url; } else { int contextPathIndex = url.indexOf(contextPath); int contextPathLength = contextPath.length(); // check to see if there is a context path in this url if (contextPathIndex >= 0) { // strip out the context path url = url.substring(0, contextPathIndex) + url.substring(contextPathIndex + contextPathLength); } // check to see if there is a leading / if (url.length() > 1 && url.charAt(0) == '/') { // remove the leading slash url = url.substring(1); } return url; } } }