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

The following examples show how to use org.springframework.security.web.savedrequest.HttpSessionRequestCache. 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
/**
 * 登陆成功,返回Token 装配此bean不支持授权码模式
 * 
 * @return
 */
@Bean
public AuthenticationSuccessHandler loginSuccessHandler() {
	return new SavedRequestAwareAuthenticationSuccessHandler() {

		private RequestCache requestCache = new HttpSessionRequestCache();

		@Override
		public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
				Authentication authentication) throws IOException, ServletException {

			super.onAuthenticationSuccess(request, response, authentication);
			return;

		}
	};
}
 
Example 2
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 3
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 4
Source Project: find   Source File: SecurityConfiguration.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("ProhibitedExceptionDeclared")
@Override
protected void configure(final HttpSecurity http) throws Exception {
    final HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
    requestCache.setRequestMatcher(new AntPathRequestMatcher(FindController.APP_PATH + "/**"));

    http
        .authorizeRequests()
            .antMatchers("/api/public/**").hasRole(FindRole.USER.name())
            .antMatchers("/api/admin/**").hasRole(FindRole.ADMIN.name())
            .antMatchers("/api/config/**").hasRole(FindRole.CONFIG.name())
            .antMatchers("/api/bi/**").hasRole(FindRole.BI.name())
            .and()
        .requestCache()
            .requestCache(requestCache)
            .and()
        .csrf()
            .disable()
        .headers()
            .defaultsDisabled()
            .frameOptions()
            .sameOrigin();
}
 
Example 5
@Override
protected final void successfulAuthentication(HttpServletRequest request,
                                              HttpServletResponse response, FilterChain chain, Authentication authResult)
        throws IOException, ServletException {

    if (logger.isDebugEnabled()) {
        logger.debug("Authentication success. Updating SecurityContextHolder to contain: "
                + authResult);
    }

    SecurityContextHolder.getContext().setAuthentication(authResult);

    // finish authentication
    User principal = authenticationService.onAuthenticationSuccess(authResult);

    // store jwt authentication cookie to secure management restricted operations
    Cookie jwtAuthenticationCookie = jwtGenerator.generateCookie(principal);
    response.addCookie(jwtAuthenticationCookie);

    // Store the saved HTTP request itself. Used by LoginController (login/callback method)
    // for redirection after successful authentication
    SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
    if (savedRequest != null && request.getSession(false) != null) {
        request.getSession(false).setAttribute(SAVED_REQUEST, savedRequest);
    }

    chain.doFilter(request, response);
}
 
Example 6
Source Project: find   Source File: InMemoryHodSecurity.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("ProhibitedExceptionDeclared")
@Override
protected void configure(final HttpSecurity http) throws Exception {
    final AuthenticationSuccessHandler loginSuccessHandler = new LoginSuccessHandler(FindRole.CONFIG.toString(), FindController.CONFIG_PATH, "/p/");
    final HttpSessionRequestCache requestCache = new HttpSessionRequestCache();

    requestCache.setRequestMatcher(new OrRequestMatcher(
            new AntPathRequestMatcher("/p/**"),
            new AntPathRequestMatcher(FindController.CONFIG_PATH)
    ));

    http.regexMatcher("/p/.*|/config/.*|/authenticate|/logout")
        .authorizeRequests()
            .antMatchers("/p/**").hasRole(FindRole.ADMIN.name())
            .antMatchers(FindController.CONFIG_PATH).hasRole(FindRole.CONFIG.name())
            .and()
        .requestCache()
            .requestCache(requestCache)
            .and()
        .formLogin()
            .loginPage(FindController.DEFAULT_LOGIN_PAGE)
            .loginProcessingUrl("/authenticate")
            .successHandler(loginSuccessHandler)
            .failureUrl(FindController.DEFAULT_LOGIN_PAGE + "?error=auth")
            .and()
        .logout()
            .logoutSuccessHandler(new HodLogoutSuccessHandler(new HodTokenLogoutSuccessHandler(SsoController.SSO_LOGOUT_PAGE, tokenRepository), FindController.APP_PATH))
            .and()
        .csrf()
            .disable();
}
 
Example 7
Source Project: Parrit   Source File: LoginController.java    License: 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 8
Source Project: promregator   Source File: SecurityConfig.java    License: Apache License 2.0 4 votes vote down vote up
private RequestCache newHttpSessionRequestCache() {
	HttpSessionRequestCache httpSessionRequestCache = new HttpSessionRequestCache();
	httpSessionRequestCache.setCreateSessionAllowed(false);
	return httpSessionRequestCache;
}
 
Example 9
Source Project: MaxKey   Source File: PermissionAdapter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, 
        HttpServletResponse response, Object handler)
        throws Exception {
    _logger.trace("PermissionAdapter preHandle");
    //save  first protected url 
    SavedRequest  firstSavedRequest = (SavedRequest)WebContext.getAttribute(WebConstants.FIRST_SAVED_REQUEST_PARAMETER);
    // 判断用户是否登录, 判断用户和角色,判断用户是否登录用户
    if  (WebContext.getAuthentication() == null 
            || WebContext.getAuthentication().getAuthorities() == null) {
        //保存未认证的请求信息
        if(firstSavedRequest==null){
            RequestCache requestCache = new HttpSessionRequestCache();
            requestCache.saveRequest(request, response);
            SavedRequest  savedRequest =requestCache.getRequest(request, response);
            if(savedRequest!=null){
                _logger.debug("first request parameter  savedRequest "+savedRequest.getRedirectUrl());
                WebContext.setAttribute(WebConstants.FIRST_SAVED_REQUEST_PARAMETER, savedRequest);
                savedRequestSuccessHandler.setRequestCache(requestCache);
            }
        }
        
        _logger.trace("No Authentication ... forward to /login");
        RequestDispatcher dispatcher = request.getRequestDispatcher("/login");
        dispatcher.forward(request, response);
        return false;
    }
    
    //认证完成,跳转到未认证请求
    if(firstSavedRequest!=null) {
        savedRequestSuccessHandler.onAuthenticationSuccess(request, response, WebContext.getAuthentication());
        WebContext.removeAttribute(WebConstants.FIRST_SAVED_REQUEST_PARAMETER);
    }

    boolean hasAccess = true;

    /*
     * boolean preHandler = super.preHandle(request, response, handler);
     * 
     * if(preHandler) { preHandler = false;
     * 
     * 
     * if(!preHandler){//无权限转向
     * log.debug("You do not have permission to access "+accessUrl);
     * RequestDispatcher dispatcher = request.getRequestDispatcher("/accessdeny");
     * dispatcher.forward(request, response); return false; } }
     */
    return hasAccess;
}
 
Example 10
Source Project: lolibox   Source File: SocialConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public ProviderSignInController providerSignInController(ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository) {
    return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new SimpleSignInAdapter(new HttpSessionRequestCache()));
}