2017-03-08 323 views
1

我實現了一個成功處理程序,將用戶重定向到某個頁面,如果他或她是管理員用戶。如何使用AuthenticationSuccessHandler將用戶重定向到頁面?

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方法,他或她會被髮送到默認頁面/index.html

@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

由於您已經在重定向url中提供了請求上下文,您需要在重定向策略中設置contextRelative = true,以便它在最終重定向url中忽略請求上下文。

DefaultRedirectStrategy REDIRECT_STRATEGY = new DefaultRedirectStrategy(); 
REDIRECT_STRATEGY.setContextRelative(true); 
相關問題