如何使用AuthenticationSuccessHandler将用户重定向到页面?

时间:2017-03-08 16:39:42

标签: java spring spring-mvc redirect spring-security

我实施了一个成功处理程序,如果用户是管理员用户,会将用户重定向到某个页面。

public class MaunaKeaAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

  private static final RedirectStrategy REDIRECT_STRATEGY = new DefaultRedirectStrategy();

  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    if (isMkeaAdmin(authentication)) {
      REDIRECT_STRATEGY.sendRedirect(request, response, "/admin/submission-queue.html");
    }
  }

  private static boolean isMkeaAdmin(Authentication authentication) {
    if (!(authentication.getPrincipal() instanceof AccountUserDetailsAdapter)) {
      return false;
    }
    AccountUserDetailsAdapter userDetails = (AccountUserDetailsAdapter) authentication.getPrincipal();
    return userDetails.getAccount().getRoles().contains("MKEA_Admin");
  }

}

调用onAuthenticationSuccess方法,并调用sendRedirect方法。但是用户没有被重定向。相反,由于我的控制器中有/index.html方法,他或她会被发送到默认页面index

@PreAuthorize("hasAnyAuthority('PERM_CAN_LOGIN')")
@RequestMapping(value="/index.html")
public String index(HttpServletRequest request, Model model) {
    WebUtils.activeNav(NAV_HOME);
    return viewRegistry.getPath("main.index");
}

以下是我spring-security.xml的一部分。

<beans:bean id="casFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter"
  p:authenticationManager-ref="authenticationManager">
  <beans:property name="authenticationSuccessHandler">
    <beans:bean class="gov.ehawaii.maunakea.security.MaunaKeaAuthenticationSuccessHandler"/>
  </beans:property>
</beans:bean>

如何实现重定向,以便不调用控制器中的index方法?

1 个答案:

答案 0 :(得分:1)

由于您已在重定向URL中提供了请求上下文。您需要在重定向策略中设置contextRelative = true,以便它忽略最终重定向URL中的请求上下文。

DefaultRedirectStrategy REDIRECT_STRATEGY = new DefaultRedirectStrategy();
REDIRECT_STRATEGY.setContextRelative(true);