Java 类org.springframework.security.web.savedrequest.DefaultSavedRequest 实例源码

项目:GitHub    文件:DefaultSavedRequestTest.java   
public void test_for_issue() throws Exception {
        MockHttpServletRequest mockReq = new MockHttpServletRequest();
        DefaultSavedRequest request = new DefaultSavedRequest(mockReq, new PortResolver() {

            public int getServerPort(ServletRequest servletRequest) {
                return 0;
            }
        });

        String str = JSON.toJSONString(request, SerializerFeature.WriteClassName);
//        System.out.println(str);


        JSON.parseObject(str, Object.class, config);

        JSON.parseObject(str);
    }
项目:cloud-native-microservice-strangler-example    文件:LoginController.java   
/**
 * Generate an authorization parameter map from the session's token request
 * @param defaultSavedRequest the default saved request from the session
 * @return a map of parameters containing the OAuth2 request details
 */
private Map<String, String> getAuthParameters(DefaultSavedRequest defaultSavedRequest) {
    Map<String, String> authParams = new HashMap<>();

    authParams.put(OAuth2Utils.CLIENT_ID,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.CLIENT_ID)[0]);

    authParams.put(OAuth2Utils.REDIRECT_URI,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.REDIRECT_URI)[0]);

    if(defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE) != null) {
        authParams.put(OAuth2Utils.STATE,
                defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE)[0]);
    }

    authParams.put(OAuth2Utils.RESPONSE_TYPE, "code");
    authParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    authParams.put(OAuth2Utils.GRANT_TYPE, "authorization_code");
    return authParams;
}
项目:spring-cloud-event-sourcing-example    文件:LoginController.java   
/**
 * Generate an authorization parameter map from the session's token request
 * @param defaultSavedRequest the default saved request from the session
 * @return a map of parameters containing the OAuth2 request details
 */
private Map<String, String> getAuthParameters(DefaultSavedRequest defaultSavedRequest) {
    Map<String, String> authParams = new HashMap<>();

    authParams.put(OAuth2Utils.CLIENT_ID,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.CLIENT_ID)[0]);

    authParams.put(OAuth2Utils.REDIRECT_URI,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.REDIRECT_URI)[0]);

    if(defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE) != null) {
        authParams.put(OAuth2Utils.STATE,
                defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE)[0]);
    }

    authParams.put(OAuth2Utils.RESPONSE_TYPE, "code");
    authParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    authParams.put(OAuth2Utils.GRANT_TYPE, "authorization_code");
    return authParams;
}
项目:eHMP    文件:AuthControllerTests.java   
@Test
public void testDisplayLoginPageWithOriginalSavedRequestIfSetupComplete() throws Exception {
    when(mockEnvironment.getProperty(SETUP_COMPLETE)).thenReturn("true");
    when(mockEnvironment.getProperty(HmpProperties.VERSION)).thenReturn("fred");
    when(mockSyncService.isOperationalSynching()).thenReturn(Boolean.FALSE);
    when(mockSyncService.isReindexAllComplete()).thenReturn(Boolean.TRUE);
    when(mockSyncService.isDataStreamEnabled()).thenReturn(Boolean.TRUE);

    MockHttpServletRequest mockOriginalRequest = new MockHttpServletRequest();
    mockOriginalRequest.setScheme("https");
    mockOriginalRequest.setServerName("example.org");
    mockOriginalRequest.setServerPort(3333);
    mockOriginalRequest.setRequestURI("/foo/bar/baz");

    PortResolver mockPortResolver = mock(PortResolver.class);
    when(mockPortResolver.getServerPort(mockOriginalRequest)).thenReturn(3333);

    // spring security will have put the original request in the session
    mockSession.setAttribute("SPRING_SECURITY_SAVED_REQUEST", new DefaultSavedRequest(mockOriginalRequest, mockPortResolver));

    ModelAndView mav = c.login(mockRequest, mockResponse);
    assertThat(mav.getViewName(), equalTo("/auth/login"));
    assertThat(((String) mav.getModel().get("hmpVersion")), equalTo("fred"));
}
项目:eHMP    文件:AuthControllerTests.java   
@Test
public void testDisplayLoginPageAfterAjaxRequestWhichFailedDueToExpiredSession() throws Exception {
    when(mockEnvironment.getProperty(SETUP_COMPLETE)).thenReturn("true");
    when(mockEnvironment.getProperty(HmpProperties.VERSION)).thenReturn("fred");
    when(mockSyncService.isOperationalSynching()).thenReturn(Boolean.FALSE);
    when(mockSyncService.isReindexAllComplete()).thenReturn(Boolean.TRUE);
    when(mockSyncService.isDataStreamEnabled()).thenReturn(Boolean.TRUE);

    MockHttpServletRequest mockOriginalRequest = new MockHttpServletRequest();
    mockOriginalRequest.addHeader("X-Requested-With", "XMLHttpRequest");
    mockOriginalRequest.setScheme("https");
    mockOriginalRequest.setServerName("example.org");
    mockOriginalRequest.setServerPort(3333);
    mockOriginalRequest.setRequestURI("/foo/bar/baz");

    PortResolver mockPortResolver = mock(PortResolver.class);
    when(mockPortResolver.getServerPort(mockOriginalRequest)).thenReturn(3333);

    // spring security will have put the original request in the session
    mockSession.setAttribute("SPRING_SECURITY_SAVED_REQUEST", new DefaultSavedRequest(mockOriginalRequest, mockPortResolver));

    ModelAndView mav = c.login(mockRequest, mockResponse);
    assertThat(mav.getViewName(), equalTo("/auth/login"));
    assertThat(((String) mav.getModel().get("hmpVersion")), equalTo("fred"));
}
项目:eHMP    文件:AuthControllerTests.java   
@Test
public void testDisplaySyncStatusPageWhenOperationalSyncIncomplete() throws Exception {
    when(mockEnvironment.getProperty(SETUP_COMPLETE)).thenReturn("true");
    when(mockEnvironment.getProperty(HmpProperties.VERSION)).thenReturn("fred");
    when(mockSyncService.isOperationalSynching()).thenReturn(Boolean.TRUE);

    MockHttpServletRequest mockOriginalRequest = new MockHttpServletRequest();
    mockOriginalRequest.addHeader("X-Requested-With", "XMLHttpRequest");
    mockOriginalRequest.setScheme("https");
    mockOriginalRequest.setServerName("example.org");
    mockOriginalRequest.setServerPort(3333);
    mockOriginalRequest.setRequestURI("/foo/bar/baz");

    PortResolver mockPortResolver = mock(PortResolver.class);
    when(mockPortResolver.getServerPort(mockOriginalRequest)).thenReturn(3333);

    // spring security will have put the original request in the session
    mockSession.setAttribute("SPRING_SECURITY_SAVED_REQUEST", new DefaultSavedRequest(mockOriginalRequest, mockPortResolver));

    ModelAndView mav = c.login(mockRequest, mockResponse);
    assertThat(mav.getViewName(), equalTo("/auth/initializing"));
    assertThat(((String) mav.getModel().get("hmpVersion")), equalTo("fred"));
}
项目:eHMP    文件:AuthControllerTests.java   
@Test
public void testDisplayReindexStatusPageWhenReindexingIncomplete() throws Exception {
    when(mockEnvironment.getProperty(SETUP_COMPLETE)).thenReturn("true");
    when(mockEnvironment.getProperty(HmpProperties.VERSION)).thenReturn("fred");
    when(mockSyncService.isOperationalSynching()).thenReturn(Boolean.FALSE);
    when(mockSyncService.isReindexAllComplete()).thenReturn(Boolean.FALSE);

    MockHttpServletRequest mockOriginalRequest = new MockHttpServletRequest();
    mockOriginalRequest.addHeader("X-Requested-With", "XMLHttpRequest");
    mockOriginalRequest.setScheme("https");
    mockOriginalRequest.setServerName("example.org");
    mockOriginalRequest.setServerPort(3333);
    mockOriginalRequest.setRequestURI("/foo/bar/baz");

    PortResolver mockPortResolver = mock(PortResolver.class);
    when(mockPortResolver.getServerPort(mockOriginalRequest)).thenReturn(3333);

    // spring security will have put the original request in the session
    mockSession.setAttribute("SPRING_SECURITY_SAVED_REQUEST", new DefaultSavedRequest(mockOriginalRequest, mockPortResolver));

    ModelAndView mav = c.login(mockRequest, mockResponse);
    assertThat(mav.getViewName(), equalTo("/auth/reindexing"));
    assertThat(((String) mav.getModel().get("hmpVersion")), equalTo("fred"));
}
项目:microservices-event-sourcing    文件:LoginController.java   
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
    HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
    httpSessionSecurityContextRepository.loadContext(holder);

    try {
        // 使用提供的证书认证用户
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN");
        Authentication auth = new UsernamePasswordAuthenticationToken(request.getParameter("username"), request.getParameter("password"), authorities);
        SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(auth));

        // 认证用户
        if(!auth.isAuthenticated())
            throw new CredentialException("用户不能够被认证");
    } catch (Exception ex) {
        // 用户不能够被认证,重定向回登录页
        logger.info(ex);
        return "login";
    }

    // 从会话得到默认保存的请求
    DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
    // 为令牌请求生成认证参数Map
    Map<String, String> authParams = getAuthParameters(defaultSavedRequest);
    AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clientDetailsService).createAuthorizationRequest(authParams);
    authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
    model.addAttribute("authorizationRequest", authRequest);

    httpSessionSecurityContextRepository.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
    return "authorize";
}
项目:microservices-event-sourcing    文件:LoginController.java   
/**
 * 为会话的令牌请求生成认证参数Map
 * @param defaultSavedRequest 会话中默认保存的SPRING_SECURITY_SAVED_REQUEST请求
 * @return 包含OAuth2请求明细的参数Map
 */
private Map<String,String> getAuthParameters(DefaultSavedRequest defaultSavedRequest) {
    Map<String, String> authParams = new HashMap<>();
    authParams.put(OAuth2Utils.CLIENT_ID, defaultSavedRequest.getParameterMap().get(OAuth2Utils.CLIENT_ID)[0]);
    authParams.put(OAuth2Utils.REDIRECT_URI, defaultSavedRequest.getParameterMap().get(OAuth2Utils.REDIRECT_URI)[0]);
    if(defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE) != null) {
        authParams.put(OAuth2Utils.STATE, defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE)[0]);
    }

    authParams.put(OAuth2Utils.RESPONSE_TYPE, "code");
    authParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    authParams.put(OAuth2Utils.GRANT_TYPE, "authorization_code");

    return authParams;
}
项目:eHMP    文件:AuthControllerTests.java   
@Test
public void testDisplayDataStreamErrorPageWhenDataStreamFailure() throws Exception {
    when(mockEnvironment.getProperty(SETUP_COMPLETE)).thenReturn("true");
    when(mockEnvironment.getProperty(HmpProperties.VERSION)).thenReturn("fred");
    when(mockSyncService.isReindexAllComplete()).thenReturn(Boolean.TRUE);
    when(mockSyncService.isOperationalSynching()).thenReturn(Boolean.FALSE);
    when(mockSyncService.isDataStreamEnabled()).thenReturn(Boolean.FALSE);
    Map<String, Object> derr = new HashMap<>();
    derr.put("disableMsg","There's a bar stuck in the foo");
    when(mockSyncService.getDataStreamErrorDetails()).thenReturn(derr);

    MockHttpServletRequest mockOriginalRequest = new MockHttpServletRequest();
    mockOriginalRequest.addHeader("X-Requested-With", "XMLHttpRequest");
    mockOriginalRequest.setScheme("https");
    mockOriginalRequest.setServerName("example.org");
    mockOriginalRequest.setServerPort(3333);
    mockOriginalRequest.setRequestURI("/foo/bar/baz");

    PortResolver mockPortResolver = mock(PortResolver.class);
    when(mockPortResolver.getServerPort(mockOriginalRequest)).thenReturn(3333);

    // spring security will have put the original request in the session
    mockSession.setAttribute("SPRING_SECURITY_SAVED_REQUEST", new DefaultSavedRequest(mockOriginalRequest, mockPortResolver));

    ModelAndView mav = c.login(mockRequest, mockResponse);
    assertThat(mav.getViewName(), equalTo("/auth/dataStreamError"));
    assertThat(((String) mav.getModel().get("hmpVersion")), equalTo("fred"));
}
项目:para    文件:SimpleRequestCache.java   
/**
 * Saves a request in cache.
 * @param request HTTP request
 * @param response HTTP response
 */
@Override
public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
    if (anyRequestMatcher.matches(request) && !ajaxRequestMatcher.matches(request)) {
        DefaultSavedRequest savedRequest = new DefaultSavedRequest(request, portResolver);
        HttpUtils.setStateParam(Config.RETURNTO_COOKIE,
                Utils.base64enc(savedRequest.getRedirectUrl().getBytes()), request, response);
    }
}
项目:LearningAnalyticsProcessor    文件:SecurityConfig.java   
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
    HttpServletResponse response, Authentication authentication)
    throws ServletException, IOException {
  DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) request
      .getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY");

  if (defaultSavedRequest != null) {
    log.debug("saved url: " + defaultSavedRequest.getRedirectUrl());
    getRedirectStrategy().sendRedirect(request, response,
        defaultSavedRequest.getRedirectUrl());
  } else {
    super.onAuthenticationSuccess(request, response, authentication);
  }
}
项目:cloud-native-microservice-strangler-example    文件:LoginController.java   
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {

    HttpRequestResponseHolder responseHolder = new HttpRequestResponseHolder(request, response);
    sessionRepository.loadContext(responseHolder);

    try {
        // Authenticate the user with the supplied credentials
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN");

        Authentication auth =
                new UsernamePasswordAuthenticationToken(request.getParameter("username"),
                        request.getParameter("password"), authorities);

        SecurityContextHolder.getContext()
                .setAuthentication(authenticationManager.authenticate(auth));

        // Authenticate the user
        if(!authenticationManager.authenticate(auth).isAuthenticated())
            throw new CredentialException("User could not be authenticated");

    } catch (Exception ex) {
        // The user couldn't be authenticated, redirect back to login
        ex.printStackTrace();
        return "login";
    }

    // Get the default saved request from session
    DefaultSavedRequest defaultSavedRequest = ((DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST"));

    // Generate an authorization parameter map for the token request
    Map<String, String> authParams = getAuthParameters(defaultSavedRequest);

    // Create the authorization request and put it in the view model
    AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clients).createAuthorizationRequest(authParams);
    authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
    sessionRepository.saveContext(SecurityContextHolder.getContext(), responseHolder.getRequest(), responseHolder.getResponse());
    model.addAttribute("authorizationRequest", authRequest);

    // Return the token authorization view
    return "authorize";
}
项目:spring-cloud-event-sourcing-example    文件:LoginController.java   
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {

    HttpRequestResponseHolder responseHolder = new HttpRequestResponseHolder(request, response);
    sessionRepository.loadContext(responseHolder);

    try {
        // Authenticate the user with the supplied credentials
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN");

        Authentication auth =
                new UsernamePasswordAuthenticationToken(request.getParameter("username"),
                        request.getParameter("password"), authorities);

        SecurityContextHolder.getContext()
                .setAuthentication(authenticationManager.authenticate(auth));

        // Authenticate the user
        if(!authenticationManager.authenticate(auth).isAuthenticated())
            throw new CredentialException("User could not be authenticated");

    } catch (Exception ex) {
        // The user couldn't be authenticated, redirect back to login
        ex.printStackTrace();
        return "login";
    }

    // Get the default saved request from session
    DefaultSavedRequest defaultSavedRequest = ((DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST"));

    // Generate an authorization parameter map for the token request
    Map<String, String> authParams = getAuthParameters(defaultSavedRequest);

    // Create the authorization request and put it in the view model
    AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clients).createAuthorizationRequest(authParams);
    authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
    sessionRepository.saveContext(SecurityContextHolder.getContext(), responseHolder.getRequest(), responseHolder.getResponse());
    model.addAttribute("authorizationRequest", authRequest);

    // Return the token authorization view
    return "authorize";
}
项目:webapp    文件:MainContentController.java   
@RequestMapping(method = RequestMethod.GET)
public String handleRequest(
        HttpServletRequest request, 
        HttpSession session, 
        Principal principal, 
        Model model) {
    logger.info("handleRequest");

    // Check if the Contributor has not yet provided all required details
    Contributor contributor = (Contributor) session.getAttribute("contributor");
    if (StringUtils.isBlank(contributor.getEmail())) {
        return "redirect:/content/contributor/add-email";
    } else if (StringUtils.isBlank(contributor.getFirstName()) || StringUtils.isBlank(contributor.getLastName())) {
        return "redirect:/content/contributor/edit-name";
    } else if (contributor.getLocale() == null) {
        return "redirect:/content/contributor/edit-locale";
    } else if ((contributor.getTeams() == null) || contributor.getTeams().isEmpty()) {
        return "redirect:/content/contributor/edit-teams";
    } else if (StringUtils.isBlank(contributor.getMotivation())) {
        return "redirect:/content/contributor/edit-motivation";
    } else if (contributor.getTimePerWeek() == null) {
        return "redirect:/content/contributor/edit-time";
    } else {
        // Redirect to originally requested URL
        DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
        logger.info("defaultSavedRequest: " + defaultSavedRequest);
        if (defaultSavedRequest != null) {
            logger.info("Redirecting to " + defaultSavedRequest.getServletPath());
            return "redirect:" + defaultSavedRequest.getServletPath();
        }
    }

    model.addAttribute("numberCount", numberDao.readCount(contributor.getLocale()));
    model.addAttribute("letterCount", letterDao.readCount(contributor.getLocale()));
    model.addAttribute("syllableCount", syllableDao.readCount(contributor.getLocale()));
    model.addAttribute("wordCount", wordDao.readCount(contributor.getLocale()));
    model.addAttribute("storyBookCount", storyBookDao.readCount(contributor.getLocale()));
    model.addAttribute("audioCount", audioDao.readCount(contributor.getLocale()));
    model.addAttribute("imageCount", imageDao.readCount(contributor.getLocale()));
    model.addAttribute("videoCount", videoDao.readCount(contributor.getLocale()));

    return "content/main";
}
项目:eHMP    文件:WebUtilsTests.java   
@Test
public void testSavedRequestIsNotAjax() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    SavedRequest savedRequest = new DefaultSavedRequest(request, mockPortResolver);
    assertThat(WebUtils.isAjax(savedRequest), equalTo(false));
}
项目:oauth-client-master    文件:OAuthConsumerContextFilter.java   
/**
 * Get the callback URL for the specified request.
 *
 * @param request The request.
 * @return The callback URL.
 */
protected String getCallbackURL(HttpServletRequest request) {
    return new DefaultSavedRequest(request, getPortResolver()).getRedirectUrl();
}