Java Code Examples for org.springframework.security.web.savedrequest.SavedRequest#getRedirectUrl()

The following examples show how to use org.springframework.security.web.savedrequest.SavedRequest#getRedirectUrl() . 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: 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 2
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 3
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 4
Source File: SavedRequestAwareAuthenticationSuccessHandler.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws ServletException, IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);

    remeberMeService.createRemeberMe(
            authentication.getPrincipal().toString(), 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);

    // Use the DefaultSavedRequest URL
    String targetUrl = savedRequest.getRedirectUrl();

    // is cas login , with service parameter
    logger.info("CAS " + request.getParameter(WebConstants.CAS_SERVICE_PARAMETER));
    if (request.getParameter(WebConstants.CAS_SERVICE_PARAMETER) != null
            && request.getParameter(WebConstants.CAS_SERVICE_PARAMETER).startsWith("http")) {
        targetUrl = WebContext.getHttpContextPath() + "/authorize/cas/login?service="
                + request.getParameter(WebConstants.CAS_SERVICE_PARAMETER);
    }
    targetUrl = targetUrl == null ? "/forwardindex" : targetUrl;
    logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
    getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
 
Example 5
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 6
Source File: LoginPage.java    From webanno with Apache License 2.0 5 votes vote down vote up
private String getRedirectUrl()
{
    String redirectUrl = null;

    HttpSession session = ((ServletWebRequest) RequestCycle.get().getRequest())
            .getContainerRequest().getSession(false);
    if (session != null) {
        SavedRequest savedRequest = (SavedRequest) session
                .getAttribute("SPRING_SECURITY_SAVED_REQUEST");
        if (savedRequest != null) {
            redirectUrl = savedRequest.getRedirectUrl();
        }
    }

    // There is some kind of bug that logs the user out again if the redirect page is
    // the context root and if that does not end in a slash. To avoid this, we add a slash
    // here. This is rather a hack, but I have no idea why this problem occurs. Figured this
    // out through trial-and-error rather then by in-depth debugging.
    String baseUrl = RequestCycle.get().getUrlRenderer().renderFullUrl(Url.parse(""));
    if (baseUrl.equals(redirectUrl)) {
        redirectUrl += "/";
    }

    // In case there was a URL fragment in the original URL, append it again to the redirect
    // URL.
    if (redirectUrl != null && isNotBlank(form.urlfragment)) {
        redirectUrl += "#" + form.urlfragment;
    }

    return redirectUrl;
}
 
Example 7
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 8
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 9
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 10
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 11
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 12
Source File: UnAuthorizedController.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@GetMapping("/unauthorized")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String unauthorized(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        log.info("{} 需要认证后才能访问", targetUrl);
        redirectStrategy.sendRedirect(request, response, "/auth/login.html");
    }
    return "访问的资源需要身份认证!";
}
 
Example 13
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 14
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 15
Source File: UsernamePasswordAuthenticationSuccessHandler.java    From Taroco with Apache License 2.0 5 votes vote down vote up
@Override
public void onAuthenticationSuccess(final HttpServletRequest request,
                                    final HttpServletResponse response,
                                    final Authentication authentication) throws IOException, ServletException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    String redirectUri = null;
    if (savedRequest != null) {
        redirectUri = savedRequest.getRedirectUrl();
    }
    clearAuthenticationAttributes(request);
    final Response resp = Response.success(redirectUri);
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    response.getWriter().write(objectMapper.writeValueAsString(resp));
}
 
Example 16
Source File: CustomAuthenticationSuccessHandler.java    From oauth2-client with MIT License 5 votes vote down vote up
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
                                    HttpServletResponse response, Authentication authentication)
    throws IOException, ServletException {

    String redirectUrl = "";
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null && StringUtils.isNotEmpty(savedRequest.getRedirectUrl())) {
        redirectUrl = savedRequest.getRedirectUrl();
    }


    // 根据需要设置 cookie,js携带token直接访问api接口等
    if (authentication instanceof OAuth2AuthenticationToken) {
        OAuth2AuthorizedClient client = authorizedClientService
            .loadAuthorizedClient(
                ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId(),
                authentication.getName());
        String token = client.getAccessToken().getTokenValue();
        Cookie tokenCookie = new Cookie("access_token", token);
        tokenCookie.setHttpOnly(true);
        tokenCookie.setDomain(cookieDomain);
        tokenCookie.setPath("/");
        response.addCookie(tokenCookie);
    }

    //设置回调成功的页面,
    if (StringUtils.isNotEmpty(redirectUrl)) {
        super.onAuthenticationSuccess(request, response, authentication);
    } else {
        response.sendRedirect("/");
    }

}
 
Example 17
Source File: UnAuthorizedController.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@GetMapping("/unauthorized")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String unauthorized(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        log.info("{} 需要认证后才能访问", targetUrl);
        redirectStrategy.sendRedirect(request, response, "/auth/login.html");
    }
    return "访问的资源需要身份认证!";
}
 
Example 18
Source File: LoginController.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@GetMapping("unauthorized")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String unauthorized(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        log.info("{} 需要认证后才能访问", targetUrl);
        redirectStrategy.sendRedirect(request, response, "/auth/login.html");
    }
    return "访问的资源需要身份认证!";
}
 
Example 19
Source File: LoginController.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@GetMapping("unauthorized")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String unauthorized(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        log.info("{} 需要认证后才能访问", targetUrl);
        redirectStrategy.sendRedirect(request, response, "/auth/login.html");
    }
    return "访问的资源需要身份认证!";
}
 
Example 20
Source File: AjaxAuthenticationHandler.java    From onetwo with Apache License 2.0 4 votes vote down vote up
@Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		JwtSecurityTokenInfo token = null;
		if(useJwtToken){
			token = this.jwtTokenService.generateToken(authentication);
//			response.addHeader(jwtAuthHeader, token.getToken());
			/*DataResult<?> rs = DataResults.success("登录成功!")
											.data(token)
											.build();
			String text = mapper.toJson(rs);
			ResponseUtils.renderJsonByAgent(request, response, text);*/

			StoreContext ctx = StoreContext.builder()
											.authKey(jwtAuthHeader)
											.request(request)
											.response(response)
											.cookieStorer(cookieStorer)
											.token(token)
											.build();
			jwtAuthStores.saveToken(ctx);
		}
		
		if(RequestUtils.isAjaxRequest(request)){
			String redirectUrl = this.getDefaultTargetUrl();
			String targetUrlParameter = getTargetUrlParameter();
			if (isAlwaysUseDefaultTargetUrl()
					|| (targetUrlParameter != null && StringUtils.isNotBlank(request
							.getParameter(targetUrlParameter)))) {
				redirectUrl = determineTargetUrl(request, response);
			}else{
				SavedRequest saveRequest = this.requestCache.getRequest(request, response);
				if(saveRequest!=null){
					this.requestCache.removeRequest(request, response);
					redirectUrl = saveRequest.getRedirectUrl();
					clearAuthenticationAttributes(request);
				}
			}
			
			Object data = redirectUrl;
			if(token!=null){
				data = ImmutableMap.of("redirectUrl", redirectUrl, "token", token);
			}
			DataResult<?> rs = DataResults.success("登录成功!")
//											.data(authentication.getPrincipal())
											.data(data)
											.build();
			String text = mapper.toJson(rs);
			ResponseUtils.renderJsonByAgent(request, response, text);
		}else{
			this.successHandler.onAuthenticationSuccess(request, response, authentication);
		}
    }