/** * 坑爹大全 ! * 在 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; }
private List<Filter> addFilters(MotechURLSecurityRule securityRule) throws ServletException { List<Filter> filters = new ArrayList<>(); SecurityContextRepository contextRepository = new HttpSessionSecurityContextRepository(); RequestCache requestCache = new HttpSessionRequestCache(); addSecureChannel(filters, securityRule.getProtocol()); addSecurityContextPersistenceFilter(filters, contextRepository); addLogoutFilter(filters, securityRule); addAuthenticationFilters(filters, securityRule); addRequestCacheFilter(filters, requestCache); addSecurityContextHolderAwareRequestFilter(filters); addAnonymousAuthenticationFilter(filters); addSessionManagementFilter(filters, contextRepository); addExceptionTranslationFilter(filters, requestCache, securityRule.isRest()); addFilterSecurityInterceptor(filters, securityRule); return filters; }
/** * First check for a <code>SavedRequest</code> and if none exists continue * as per {@link AbstractAuthenticationTargetUrlRequestHandler}. */ protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { SavedRequest savedRequest = new HttpSessionRequestCache().getRequest( request, response); String targetUrl = savedRequest.getRedirectUrl(); System.out.println("requested url: " + targetUrl); if (targetUrl == null) { targetUrl = determineTargetUrl(request, response); } if (response.isCommitted()) { logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); return; } getRedirectStrategy().sendRedirect(request, response, targetUrl); }
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { String userId = request.getParameter("employeeId"); if (userId != null) { response.sendRedirect(request.getContextPath() + "/emp/myview/" + userId); } else { SavedRequest savedRequest = new HttpSessionRequestCache() .getRequest(request, response); if (savedRequest != null) { response.sendRedirect(savedRequest.getRedirectUrl()); } else { response.sendRedirect(request.getContextPath() + "/"); } } }
@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(); }
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response); if (savedRequest == null) { return; } HttpSession session = request.getSession(); session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); // Use the DefaultSavedRequest URL String targetUrl = savedRequest.getRedirectUrl(); logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl); response.sendRedirect(targetUrl); }
@Bean public SignInAdapter signInAdapter(UserDetailsService userDetailsService) { RequestCache requestCache = new HttpSessionRequestCache(); return (userId, connection, request) -> { UserDetails userDetails = userDetailsService.loadUserByUsername(userId); Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); SavedRequest savedRequest = requestCache.getRequest(request.getNativeRequest(HttpServletRequest.class), request.getNativeResponse(HttpServletResponse.class)); return savedRequest == null ? null : savedRequest.getRedirectUrl(); }; }
@Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { User currentUser = getUser(SecurityContextHolder.getContext().getAuthentication()); if (currentUser == null || currentUser.isAdminAccessRequested()) { deniedHandler.handle(request, response, accessDeniedException); return; } new HttpSessionRequestCache().saveRequest(request, response); entryPoint.commence(request, response, new InsufficientAuthenticationException("Additional OAuth Scopes required", accessDeniedException)); }
/** * Gets the http session request cache. * * @return the http session request cache */ @Bean(name = "httpSessionRequestCache") public HttpSessionRequestCache getHttpSessionRequestCache() { HttpSessionRequestCache cache = new HttpSessionRequestCache(); cache.setCreateSessionAllowed(false); return cache; }
@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(); }
private String getRedirectUrl(HttpServletRequest request, HttpServletResponse response) { SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response); if (savedRequest != null) { return savedRequest.getRedirectUrl(); } return request.getContextPath() + "/"; }
private void addRequestUrlToModel(final HttpServletRequest request, final HttpServletResponse response, final Model model) { final SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response); String requestUrl = null; if (savedRequest != null) { requestUrl = savedRequest.getRedirectUrl(); } model.addAttribute("requestUrl", requestUrl); }
@Bean public SignInAdapter signInAdapter() { return new SocialSignInAdapter(new HttpSessionRequestCache()); }
@Bean public SignInAdapter signInAdapter() { return new SimpleSignInAdapter(new HttpSessionRequestCache()); }
public CustomLoginSuccessHandler(String defaultRedirectUrl, String loginUrl) { this.defaultRedirectUrl = defaultRedirectUrl; this.loginUrl = loginUrl; requestCache = new HttpSessionRequestCache(); super.setRequestCache(requestCache); }
public CasAuthenticationEntryPoint() { wrappedCasAuthEntryPoint = new org.springframework.security.cas.web.CasAuthenticationEntryPoint(); cache = new HttpSessionRequestCache(); }
@Bean public ProviderSignInController providerSignInController(ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository) { return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new SimpleSignInAdapter(new HttpSessionRequestCache())); }
/** * Default constructor */ public AuthenticationRequiredHandlerImpl() { super(); requestCache = new HttpSessionRequestCache(); }
public LoginSuccessHandlerImpl() { super(); requestCache = new HttpSessionRequestCache(); alwaysUseDefaultTargetUrl = false; }
public SavedRequestAwareProcessor() { requestCache = new HttpSessionRequestCache(); }
@Bean public RequestCache requestCache() { return new HttpSessionRequestCache(); }