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

The following examples show how to use org.springframework.security.web.savedrequest.SavedRequest. These examples are extracted from open source projects. 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 Project: FEBS-Cloud   Source File: FebsWebLoginSuccessHandler.java    License: 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 2
Source Project: fw-spring-cloud   Source File: HelloController.java    License: 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 Project: fw-spring-cloud   Source File: HelloController.java    License: 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
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 Project: jeesupport   Source File: WebSecurityConfig.java    License: 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 Project: spring-boot   Source File: SpringUtils.java    License: 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 Project: MaxKey   Source File: RealAuthenticationFailureHandler.java    License: 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 Project: MaxKey   Source File: LogoutEndpoint.java    License: 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 Project: MaxKey   Source File: LogoutEndpoint.java    License: 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
@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 Project: cxf-fediz   Source File: STSUPAuthenticationProvider.java    License: 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
@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 13
@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 14
@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 15
@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 16
@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 17
@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 18
@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 19
@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
@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 21
@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
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 23
@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 24
@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 25
@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 26
@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 27
Source Project: oauth2-client   Source File: CustomAuthenticationSuccessHandler.java    License: 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 28
@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 29
Source Project: FEBS-Security   Source File: LoginController.java    License: 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 30
Source Project: SpringAll   Source File: BrowserSecurityController.java    License: 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 "访问的资源需要身份认证!";
}