1. 程式人生 > >Spring security + cas 中,Https請求莫名變為Http請求的處理

Spring security + cas 中,Https請求莫名變為Http請求的處理

public class CrownAuthenticationSuccessHandler extends
        SavedRequestAwareAuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
            HttpServletResponse response, Authentication authentication)
            throws ServletException, IOException {
        addCCTCookie(request, response);
        request.getSession().setAttribute(Constants.USER_IN_SESSION, (UserDetail)authentication.getPrincipal());
        HttpSession session = request.getSession(false);
    DefaultSavedRequest saveRequest = null;
        if (session != null) {
        saveRequest = (DefaultSavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
        System.out.println("session is not null !!");
        }
    try {
    System.out.println("step 1: scheme = "+request.getScheme());
    if(saveRequest == null) {
    System.out.println("step 2: saveRequest is null ");
    RequestCache requestCache = new HttpSessionRequestCache();
requestCache.saveRequest(request, response);
    saveRequest = (DefaultSavedRequest) requestCache.getRequest(request, response);
   
    Field contextPathField = DefaultSavedRequest.class.getDeclaredField("contextPath");
    contextPathField.setAccessible(true);
   
    Field uriField = DefaultSavedRequest.class.getDeclaredField("requestURI");
    uriField.setAccessible(true);
    uriField.set(saveRequest, contextPathField.get(saveRequest)+"/search/tosearchinvoice.do");
    System.out.println("step 4: saveRequest.uriField is "+uriField.get(saveRequest));
   
    Field queryStringField = DefaultSavedRequest.class.getDeclaredField("queryString");
    queryStringField.setAccessible(true);
    queryStringField.set(saveRequest, null);
    }
    if("http".equalsIgnoreCase(request.getScheme())){
    System.out.println("step 2: saveRequest.getRequestURL is "+saveRequest.getRequestURL());
    Field schemeField = DefaultSavedRequest.class.getDeclaredField("scheme");
    schemeField.setAccessible(true);
    String fieldValue = (String) schemeField.get(saveRequest);
    System.out.println("2 scheme before: " + fieldValue);
   
    schemeField.setAccessible(true);
    schemeField.set(saveRequest, "https");
    String fieldValue1 = (String) schemeField.get(saveRequest);
    System.out.println("fieldValue = " + fieldValue1);
   
    Field portStringField = DefaultSavedRequest.class.getDeclaredField("serverPort");
    portStringField.setAccessible(true);
    portStringField.set(saveRequest, 443);
    }
} catch (Exception e) {
e.printStackTrace();
}
        super.onAuthenticationSuccess(request, response, authentication);

    }

}