org.springframework.security.web.savedrequest.SavedRequest Java Examples

The following examples show how to use org.springframework.security.web.savedrequest.SavedRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractLoginSuccessPage.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
protected void redirectToSavedPage() {
	AbstractCoreSession<?> session = AbstractCoreSession.get();
	
	String redirectUrl = null;
	if (StringUtils.hasText(session.getRedirectUrl())) {
		redirectUrl = session.getRedirectUrl();
	} else {
		Object savedRequest = RequestCycleUtils.getCurrentContainerRequest().getSession()
				.getAttribute(MavenArtifactNotifierSession.SPRING_SECURITY_SAVED_REQUEST);
		if (savedRequest instanceof SavedRequest) {
			redirectUrl = ((SavedRequest) savedRequest).getRedirectUrl();
		}
		RequestCycleUtils.getCurrentContainerRequest().getSession()
				.removeAttribute(MavenArtifactNotifierSession.SPRING_SECURITY_SAVED_REQUEST);
	}
	if (isUrlValid(redirectUrl)) {
		redirect(redirectUrl);
	} else {
		redirect(DashboardPage.class);
	}
}
 
Example #2
Source File: HelloController.java    From fw-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 当需要身份认证时,跳转到这里
 *
 * @param request
 * @param response
 * @return
 * @throws IOException
 */
@RequestMapping("/authentication/require")
public FwResult requireAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    SavedRequest savedRequest = requestCache.getRequest(request, response);

    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        log.info("引发跳转的请求是:" + targetUrl);
        if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
            redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
        }
    }

    return FwResult.failed("访问的服务需要身份认证,请引导用户到登录页");
}
 
Example #3
Source File: FebsWebLoginSuccessHandler.java    From FEBS-Cloud with Apache License 2.0 6 votes vote down vote up
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    HttpSession session = request.getSession(false);
    if (session != null) {
        Object attribute = session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
        log.info("跳转到登录页的地址为: {}", attribute);
    }
    if (FebsUtil.isAjaxRequest(request)) {
        FebsResponse data = new FebsResponse();
        if (savedRequest == null) {
            FebsUtil.makeFailureResponse(response, data.message("请通过授权码模式跳转到该页面"));
            return;
        }
        data.data(savedRequest.getRedirectUrl());
        FebsUtil.makeSuccessResponse(response, data);
    } else {
        if (savedRequest == null) {
            super.onAuthenticationSuccess(request, response, authentication);
            return;
        }
        clearAuthenticationAttributes(request);
        getRedirectStrategy().sendRedirect(request, response, savedRequest.getRedirectUrl());
    }
}
 
Example #4
Source File: MyAuthenticationSuccessHandler.java    From springboot-security-wechat with Apache License 2.0 6 votes vote down vote up
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
    SavedRequest savedRequest = this.requestCache.getRequest(request, response);
    if(savedRequest == null) {
        //super.onAuthenticationSuccess(request, response, authentication);
        handle(request, response, authentication);
        super.clearAuthenticationAttributes(request);
    } else {
        String targetUrlParameter = this.getTargetUrlParameter();
        if(!this.isAlwaysUseDefaultTargetUrl() && (targetUrlParameter == null || !StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
            this.clearAuthenticationAttributes(request);
            String targetUrl = savedRequest.getRedirectUrl();
            this.logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
            //this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
        } else {
            this.requestCache.removeRequest(request, response);
            //super.onAuthenticationSuccess(request, response, authentication);
            handle(request, response, authentication);
            super.clearAuthenticationAttributes(request);
        }
    }
}
 
Example #5
Source File: WebSecurityConfig.java    From jeesupport with MIT License 6 votes vote down vote up
/**
 * 登陆成功后的处理
 *
 * @return
 */
@Bean
public AuthenticationSuccessHandler successHandler(){
    return new AuthenticationSuccessHandler(){
        @Override
        public void onAuthenticationSuccess( HttpServletRequest _request, HttpServletResponse _response, Authentication _auth ) throws IOException, ServletException{
            log.debug( "--登陆成功" );

            _request.getSession().setAttribute( ISupportEL.Session_User_EL, _auth.getPrincipal() );
            sessionRegistry().registerNewSession( _request.getSession().getId(), _auth.getPrincipal() );

            RequestCache requestCache = new HttpSessionRequestCache();

            SavedRequest savedRequest = requestCache.getRequest( _request, _response );
            String       url          = null;
            if( savedRequest != null ) url = savedRequest.getRedirectUrl();
            log.debug( "--登陆后转向:" + url );

            if( url == null ) redirectStrategy().sendRedirect( _request, _response, "/" );
            else _response.sendRedirect( url );
        }
    };
}
 
Example #6
Source File: SpringUtils.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 坑爹大全 !
 * 在 spring security 中,loginPage("/login") 是个特殊的 url (其他的 url 没有此限制,非 spring security 环境也无此限制)
 * 处理 /login 的 controller ,利用 @RequestParam(value = "error", required = false) 是无法接到任何参数信息的
 * "http://localhost:8888/login?error=错误信息" 的 error 参数无法接到,不光是 error ,所有的参数都接不到
 * spring security 把  "http://localhost:8888/login?error=错误信息"
 * 处理为 "http://localhost:8888/login" ,直接发给 controller ,为啥呢?
 * 当常见的需求是,登陆成功或者不成功,还想返回 /login ,并且传递点参数 /login?error=失败
 * 无法处理
 * 但 spring security 又提供了一个 org.springframework.security.web.savedrequest.SavedRequest ,来还原原始 request,可以利用它来获取参数
 * 这么做为什么?不知道
 * 又浪费了几个小时查找资料
 *
 * @param request  GET 方式发送的 http://localhost:8888/login?error=abc&rr=dce
 * @param response
 * @return
 */
public static Map<String, String> parseSpringSecurityLoginUrlWithExtraParameters(HttpServletRequest request, HttpServletResponse response) {

    SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
    if (savedRequest == null)
        return Maps.newHashMap(); // 空 map,避免异常

    Map<String, String[]> map0 = savedRequest.getParameterMap(); //难道参数的值是个多个字符串? 为什么返回 Map<String, String[]>  ?
    Map map = new HashMap<String, String>(map0.size());

    for (Map.Entry<String, String[]> entry : map0.entrySet()) {
        map.put(entry.getKey(), entry.getValue()[0]);
    }

    MyFastJsonUtils.prettyPrint(map);

    return map;
}
 
Example #7
Source File: RealAuthenticationFailureHandler.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public void onAuthenticationFailure(HttpServletRequest request,
		HttpServletResponse response, AuthenticationException authenticationException)
		throws IOException, ServletException {
	
	SavedRequest savedRequest = requestCache.getRequest(request, response);
	
	logger.debug("saved Request: {}", savedRequest);
	
	if( authenticationException instanceof IdentityProviderAuthenticationException && savedRequest != null) {
		
		logger.warn("Authn Failure reported by the IDP.", authenticationException);
		logger.debug("Retry original request of {}", savedRequest.getRedirectUrl());
		response.sendRedirect(savedRequest.getRedirectUrl());
	}

	else {
		logger.warn("Unrecoverable authn failure. Sending to Forbidden", authenticationException);
		response.sendError(HttpServletResponse.SC_FORBIDDEN);		
	}
}
 
Example #8
Source File: LogoutEndpoint.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
private ModelAndView logoutModelAndView(
		HttpServletRequest request,
		HttpServletResponse response,
		String viewName,
		String reLoginUrl){
	ModelAndView modelAndView = new ModelAndView();
	authenticationRealm.logout(response);
	
	if(reLoginUrl!=null){
		SavedRequest  firstSavedRequest = (SavedRequest)WebContext.getAttribute(WebConstants.FIRST_SAVED_REQUEST_PARAMETER);
		reLoginUrl=WebContext.getHttpContextPath()+"/login";
		if(firstSavedRequest!=null){
			reLoginUrl= firstSavedRequest.getRedirectUrl();
			WebContext.removeAttribute(WebConstants.FIRST_SAVED_REQUEST_PARAMETER);
		}
	}
	
	_logger.debug("re Login URL : "+ reLoginUrl);
	
	modelAndView.addObject("reloginUrl",reLoginUrl);
	request.getSession().invalidate();
	SecurityContextHolder.clearContext();
	modelAndView.setViewName(viewName);
	return modelAndView;
}
 
Example #9
Source File: LogoutEndpoint.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value={"/logout"})
public ModelAndView logout(HttpServletRequest request, HttpServletResponse response){
	ModelAndView modelAndView = new ModelAndView();
	authenticationRealm.logout(response);
	SavedRequest  firstSavedRequest = (SavedRequest)WebContext.getAttribute(WebConstants.FIRST_SAVED_REQUEST_PARAMETER);
	String reLoginUrl=WebContext.getHttpContextPath()+"/login";
	if(firstSavedRequest!=null){
		reLoginUrl= firstSavedRequest.getRedirectUrl();
	}
	_logger.debug("re Login URL : "+ reLoginUrl);
	modelAndView.addObject("reloginUrl",reLoginUrl);
	request.getSession().invalidate();
		
	modelAndView.setViewName("loggedout");
return modelAndView;
}
 
Example #10
Source File: SavedRequestAwareAuthenticationSuccessHandler.java    From zxl with Apache License 2.0 6 votes vote down vote up
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
	createNewSession(request, response);
	SavedRequest savedRequest = requestCache.getRequest(request, response);
	if (savedRequest == null) {
		super.onAuthenticationSuccess(request, response, authentication);
		return;
	}
	String targetUrlParameter = getTargetUrlParameter();
	if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
		requestCache.removeRequest(request, response);
		super.onAuthenticationSuccess(request, response, authentication);
		return;
	}
	clearAuthenticationAttributes(request);
	String targetUrl = appendToken(savedRequest.getRedirectUrl(), request);
	logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
	getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
 
Example #11
Source File: STSUPAuthenticationProvider.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
/**
 * If customSTSParameter has been set, this method will lookup :
 * <ul>
 *     <ol> in http parameters</ol>
 *     <ol> if not found in the requestCache from Spring Security.
 *     This lookup is necessary whenever you use Spring Security form-login since
 *     it redirects you to an login-url and stores original request in the requestCache.</ol>
 * </ul>
 */
private String getCustomSTSParameterValue() {
    String authRealmParameter = null;
    if (getCustomSTSParameter() != null) {
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        authRealmParameter = request.getParameter(getCustomSTSParameter());
        if (authRealmParameter == null) {
            HttpServletResponse response =
                    ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
            SavedRequest savedRequest = requestCache.getRequest(request, response);
            if (savedRequest != null) {
                String[] parameterValues = savedRequest.getParameterValues(this.getCustomSTSParameter());
                if (parameterValues != null && parameterValues.length > 0) {
                    authRealmParameter = parameterValues[0];
                }
            }
        }
        LOG.debug("Found {} custom STS parameter {}", getCustomSTSParameter(), authRealmParameter);
    }
    return authRealmParameter;
}
 
Example #12
Source File: BasicAuthenticationWithRedirectToLoginFilterTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldInvokeHandler() throws IOException {
    final BasicAuthenticationWithRedirectToLoginFilter filter = new BasicAuthenticationWithRedirectToLoginFilter(null, null);

    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final String message = "foo";
    SavedRequest savedRequest = mock(SavedRequest.class);

    SessionUtils.saveRequest(request, savedRequest);
    HttpSession originalSession = request.getSession(true);

    filter.onAuthenticationFailure(request, response, message);

    assertThat(SessionUtils.getAuthenticationError(request)).isEqualTo("foo");
    assertThat(request.getSession(false)).isNotSameAs(originalSession);
    assertThat(SessionUtils.savedRequest(request)).isSameAs(savedRequest);
    assertThat(SessionUtils.hasAuthenticationToken(request)).isFalse();

    MockHttpServletResponseAssert.assertThat(response)
            .redirectsTo("/go/auth/login");
}
 
Example #13
Source File: UserEnabledCheckFilterWithRedirectToLoginPageTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldRedirectToLoginPageWithAnErrorMessageInTheSession() throws IOException {
    SavedRequest savedRequest = mock(SavedRequest.class);
    SessionUtils.saveRequest(request, savedRequest);
    HttpSession originalSession = request.getSession(true);

    filter.handleFailure(request, response, "something bad happened!");

    assertThat(SessionUtils.getAuthenticationError(request)).isEqualTo("something bad happened!");
    assertThat(request.getSession(false)).isNotSameAs(originalSession);
    assertThat(SessionUtils.savedRequest(request)).isSameAs(savedRequest);
    assertThat(SessionUtils.hasAuthenticationToken(request)).isFalse();

    MockHttpServletResponseAssert.assertThat(response).redirectsTo("/go/auth/login");
    assertThat(SessionUtils.getAuthenticationError(request)).isEqualTo("something bad happened!");
}
 
Example #14
Source File: MySavedRequestAwareAuthenticationSuccessHandler.java    From springrest-angularjs with Apache License 2.0 6 votes vote down vote up
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException {
    final SavedRequest savedRequest = requestCache.getRequest(request, response);

    if (savedRequest == null) {
        clearAuthenticationAttributes(request);
        return;
    }
    final String targetUrlParameter = getTargetUrlParameter();
    if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
        requestCache.removeRequest(request, response);
        clearAuthenticationAttributes(request);
        return;
    }

    clearAuthenticationAttributes(request);

    // Use the DefaultSavedRequest URL
    // final String targetUrl = savedRequest.getRedirectUrl();
    // logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
    // getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
 
Example #15
Source File: MolgenisLoginControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void getLoginPageAuthenticated() {
  MolgenisLoginController controller = new MolgenisLoginController();

  Model model = mock(Model.class);
  HttpServletRequest request = mock(HttpServletRequest.class);
  HttpSession session = mock(HttpSession.class);
  SavedRequest savedRequest = mock(SavedRequest.class);
  SecurityContext securityContext = mock(SecurityContext.class);
  Cookie cookie = mock(Cookie.class);
  Authentication authentication = mock(Authentication.class);

  when(cookie.getName()).thenReturn("JSESSIONID");
  when(securityContext.getAuthentication()).thenReturn(authentication);
  when(savedRequest.getCookies()).thenReturn(Collections.singletonList(cookie));
  when(session.getAttribute(SPRING_SECURITY_SAVED_REQUEST)).thenReturn(savedRequest);
  when(session.getAttribute(SPRING_SECURITY_CONTEXT)).thenReturn(securityContext);
  when(request.getSession(false)).thenReturn(session);

  assertEquals(VIEW_LOGIN, controller.getLoginPage(request, model));
  verifyNoMoreInteractions(model);
}
 
Example #16
Source File: MolgenisLoginControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void getLoginPageExpired() {
  MolgenisLoginController controller = new MolgenisLoginController();

  Model model = mock(Model.class);
  HttpServletRequest request = mock(HttpServletRequest.class);
  HttpSession session = mock(HttpSession.class);
  SavedRequest savedRequest = mock(SavedRequest.class);
  SecurityContext securityContext = mock(SecurityContext.class);
  Cookie cookie = mock(Cookie.class);

  when(cookie.getName()).thenReturn("JSESSIONID");
  when(savedRequest.getCookies()).thenReturn(Collections.singletonList(cookie));
  when(session.getAttribute(SPRING_SECURITY_SAVED_REQUEST)).thenReturn(savedRequest);
  when(session.getAttribute(SPRING_SECURITY_CONTEXT)).thenReturn(securityContext);
  when(request.getSession(false)).thenReturn(session);

  assertEquals(VIEW_LOGIN, controller.getLoginPage(request, model));
  verify(model).addAttribute(ERROR_MESSAGE_ATTRIBUTE, ERROR_MESSAGE_SESSION_AUTHENTICATION);
}
 
Example #17
Source File: MySavedRequestAwareAuthenticationSuccessHandler.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException {
    final SavedRequest savedRequest = requestCache.getRequest(request, response);

    if (savedRequest == null) {
        clearAuthenticationAttributes(request);
        return;
    }
    final String targetUrlParameter = getTargetUrlParameter();
    if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
        requestCache.removeRequest(request, response);
        clearAuthenticationAttributes(request);
        return;
    }

    clearAuthenticationAttributes(request);
}
 
Example #18
Source File: MySavedRequestAwareAuthenticationSuccessHandler.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException {
    final SavedRequest savedRequest = requestCache.getRequest(request, response);

    if (savedRequest == null) {
        super.onAuthenticationSuccess(request, response, authentication);

        return;
    }
    final String targetUrlParameter = getTargetUrlParameter();
    if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
        requestCache.removeRequest(request, response);
        super.onAuthenticationSuccess(request, response, authentication);

        return;
    }

    clearAuthenticationAttributes(request);

    // Use the DefaultSavedRequest URL
    // final String targetUrl = savedRequest.getRedirectUrl();
    // logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
    // getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
 
Example #19
Source File: MySavedRequestAwareAuthenticationSuccessHandler.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException {
    final SavedRequest savedRequest = requestCache.getRequest(request, response);

    if (savedRequest == null) {
        super.onAuthenticationSuccess(request, response, authentication);

        return;
    }
    final String targetUrlParameter = getTargetUrlParameter();
    if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
        requestCache.removeRequest(request, response);
        super.onAuthenticationSuccess(request, response, authentication);

        return;
    }

    clearAuthenticationAttributes(request);

    // Use the DefaultSavedRequest URL
    // final String targetUrl = savedRequest.getRedirectUrl();
    // logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
    // getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
 
Example #20
Source File: ReAuthenticationWithRedirectToLoginFilterTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldInvokeHandler() throws IOException {
    final ReAuthenticationWithRedirectToLoginFilter filter = new ReAuthenticationWithRedirectToLoginFilter(null, null, null, null, null, null);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final String message = "foo";
    SavedRequest savedRequest = mock(SavedRequest.class);

    SessionUtils.saveRequest(request, savedRequest);
    HttpSession originalSession = request.getSession(true);

    filter.onAuthenticationFailure(request, response, message);

    assertThat(SessionUtils.getAuthenticationError(request)).isEqualTo("foo");
    assertThat(request.getSession(false)).isNotSameAs(originalSession);
    assertThat(SessionUtils.savedRequest(request)).isSameAs(savedRequest);
    assertThat(SessionUtils.hasAuthenticationToken(request)).isFalse();

    MockHttpServletResponseAssert.assertThat(response)
            .redirectsTo("/go/auth/login");
}
 
Example #21
Source File: MySavedRequestAwareAuthenticationSuccessHandler.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException {
    final SavedRequest savedRequest = requestCache.getRequest(request, response);

    if (savedRequest == null) {
        super.onAuthenticationSuccess(request, response, authentication);

        return;
    }
    final String targetUrlParameter = getTargetUrlParameter();
    if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
        requestCache.removeRequest(request, response);
        super.onAuthenticationSuccess(request, response, authentication);

        return;
    }

    clearAuthenticationAttributes(request);

    // Use the DefaultSavedRequest URL
    // final String targetUrl = savedRequest.getRedirectUrl();
    // logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
    // getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
 
Example #22
Source File: HelloController.java    From fw-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 当需要身份认证时,跳转到这里
 *
 * @param request
 * @param response
 * @return
 * @throws IOException
 */
@RequestMapping("/authentication/require")
public FwResult requireAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    SavedRequest savedRequest = requestCache.getRequest(request, response);

    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        log.info("引发跳转的请求是:" + targetUrl);
        if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
            redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
        }
    }

    return FwResult.failed("访问的服务需要身份认证,请重新登录");
}
 
Example #23
Source File: SimpleSignInAdapter.java    From lolibox with Apache License 2.0 5 votes vote down vote up
private String extractOriginalUrl(NativeWebRequest request) {
    HttpServletRequest nativeReq = request.getNativeRequest(HttpServletRequest.class);
    HttpServletResponse nativeRes = request.getNativeResponse(HttpServletResponse.class);
    SavedRequest saved = requestCache.getRequest(nativeReq, nativeRes);
    if (saved == null) {
        return null;
    }
    requestCache.removeRequest(nativeReq, nativeRes);
    removeAutheticationAttributes(nativeReq.getSession(false));
    return saved.getRedirectUrl();
}
 
Example #24
Source File: PlayerFormLoginSuccessAuthenticationHandler.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
private String obtainGameName(HttpServletRequest request, SavedRequest savedRequest) {
    String loginFormGameName = request.getParameter(GAME_NAME_KEY);
    String[] queryParamGameParameter = ofNullable(savedRequest.getParameterValues(GAME_NAME_KEY))
            .orElse(new String[] {});
    String queryParamGameName = queryParamGameParameter.length > 0 ? queryParamGameParameter[0] : null;

    String gameName = ofNullable(queryParamGameName)
            .orElse(loginFormGameName);

    // TODO при первой загрузке если сразу залогиниться в админку то получаем gameName == null
    // все потому что там на поле с играми стоит <c:if test="${not adminLogin}">
    log.debug("Game name was chosen: {}", gameName);

    return gameName;
}
 
Example #25
Source File: BrowserSecurityController.java    From imooc-security with Apache License 2.0 5 votes vote down vote up
/**
 * 当需要身份认证时跳转到这个controller
 *
 * @param request
 * @param response
 * @return
 */
@RequestMapping("/authentication/require")
public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        logger.info("引发跳转的请求是:"+targetUrl);
        if(StringUtils.endsWithIgnoreCase(targetUrl,".html")){
            redirectStrategy.sendRedirect(request,response,properties.getBrowser().getLoginPage());
        }
    }
    return new SimpleResponse("访问的服务器需要身份认证,请引导用户到登录页面");
}
 
Example #26
Source File: BrowserSecurityController.java    From SpringAll with MIT License 5 votes vote down vote up
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
            redirectStrategy.sendRedirect(request, response, "/login.html");
    }
    return "访问的资源需要身份认证!";
}
 
Example #27
Source File: BrowserSecurityController.java    From SpringAll with MIT License 5 votes vote down vote up
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
            redirectStrategy.sendRedirect(request, response, "/login.html");
    }
    return "访问的资源需要身份认证!";
}
 
Example #28
Source File: LoginController.java    From FEBS-Security with Apache License 2.0 5 votes vote down vote up
@GetMapping("/login")
public String login(HttpServletRequest request, HttpServletResponse response) {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String redirectUrl = savedRequest.getRedirectUrl();
        log.info("引发跳转的请求是:{}", redirectUrl);
    }
    return "login";
}
 
Example #29
Source File: LoginController.java    From Parrit with MIT License 5 votes vote down vote up
@RequestMapping(path = "/login", method = RequestMethod.GET)
public String loginProject(final HttpServletRequest request, final HttpServletResponse response, Model model) {
    SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);

    //TODO: Check to make sure this isn't null -- maybe redirect to homepage if it is
    String originalRequestUrl = savedRequest.getRedirectUrl();
    String projectName = originalRequestUrl.substring(originalRequestUrl.lastIndexOf('/') + 1);
    projectName = UriUtils.decode(projectName, Charset.defaultCharset());

    model.addAttribute("projectName", projectName);
    return "login";
}
 
Example #30
Source File: SessionUtils.java    From gocd with Apache License 2.0 5 votes vote down vote up
public static void redirectToLoginPage(HttpServletRequest request, HttpServletResponse response, String errorMessage) throws IOException {
    SavedRequest savedRequest = SessionUtils.savedRequest(request);
    SessionUtils.recreateSessionWithoutCopyingOverSessionState(request);

    SessionUtils.saveRequest(request, savedRequest);
    SessionUtils.setAuthenticationError(errorMessage, request);
    response.sendRedirect("/go/auth/login");
}