List of usage examples for org.springframework.security.core.context SecurityContextHolder clearContext
public static void clearContext()
From source file:business.SelectionControllerTests.java
@Test(groups = "request", dependsOnMethods = "submitRequestForApproval") public void approveRequest() { UserAuthenticationToken palga = getPalga(); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(palga); RequestRepresentation representation = requestController.getRequestById(palga, processInstanceId); log.info("Status: " + representation.getStatus()); representation = requestController.claim(palga, processInstanceId, representation); representation.setPrivacyCommitteeRationale("ppc_approved_written_procedure"); representation.setScientificCouncilApproved(true); representation.setPrivacyCommitteeApproved(true); representation = requestController.finalise(palga, processInstanceId, representation); log.info("Status: " + representation.getStatus()); assertEquals(RequestStatus.DATA_DELIVERY, representation.getStatus()); SecurityContextHolder.clearContext(); }
From source file:de.blizzy.documentr.web.page.PageControllerTest.java
@Test public void getPageMustReturn404IfNotFound() throws IOException { when(request.getDateHeader(anyString())).thenReturn(-1L); when(pageStore.getPageMetadata(eq(PROJECT), eq(BRANCH), eq("nonexistent"))) //$NON-NLS-1$ .thenThrow(new PageNotFoundException(PROJECT, BRANCH, "nonexistent")); //$NON-NLS-1$ SecurityContextHolder.setContext(createSecurityContext(authenticatedAuthentication)); String view = pageController.getPage(PROJECT, BRANCH, "nonexistent", model, request, response); //$NON-NLS-1$ SecurityContextHolder.clearContext(); assertEquals("/error/" + HttpServletResponse.SC_NOT_FOUND + "/page.notFound", removeViewPrefix(view)); //$NON-NLS-1$ //$NON-NLS-2$ assertForward(view);/*from w w w .j a v a2 s. co m*/ }
From source file:business.UploadTests.java
@Test(groups = "upload", dependsOnMethods = "createRequest") public void uploadFileSuccess() throws IOException { UserAuthenticationToken requester = getRequester(); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(requester); RequestRepresentation representation = requestController.getRequestById(requester, processInstanceId); log.info("Status: " + representation.getStatus()); int attachmentCount = representation.getAttachments().size(); ClassLoader classLoader = getClass().getClassLoader(); URL resource = classLoader.getResource("test/Utrecht_Oude_Gracht_Hamburgerbrug_(LOC).jpg"); InputStream input = resource.openStream(); MultipartFile file = new MockMultipartFile(resource.getFile(), resource.getFile().toString(), "image/jpeg", input);/*from w ww.ja v a 2 s. co m*/ Integer flowTotalChunks = 1; Integer flowChunkNumber = 1; String flowIdentifier = "flow"; representation = requestController.uploadRequestAttachment(requester, processInstanceId, resource.getFile(), flowTotalChunks, flowChunkNumber, flowIdentifier, file); assertEquals(attachmentCount + 1, representation.getAttachments().size()); printFiles(representation.getAttachments()); SecurityContextHolder.clearContext(); }
From source file:com.telefonica.euro_iaas.sdc.puppetwrapper.auth.OpenStackAuthenticationFilter.java
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final boolean info = logger.isInfoEnabled(); final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; String header = request.getHeader(OPENSTACK_HEADER_TOKEN); String pathInfo = request.getPathInfo(); MDC.put("txId", ((HttpServletRequest) req).getSession().getId()); if (pathInfo.equals("/") || pathInfo.equals("/extensions")) { /**//from w ww . ja v a 2 s . co m * It is not needed to authenticate these operations */ logger.info("Operation does not need to Authenticate"); } else { if (header == null) { header = ""; } try { String token = header; if ("".equals(token)) { String str = "Missing token header"; logger.info(str); throw new BadCredentialsException(str); } String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID); String txId = request.getHeader("txId"); if (txId != null) { MDC.put("txId", txId); } // String tenantId = request.getPathInfo().split("/")[3]; if (info) { logger.info("OpenStack Authentication Authorization header " + "found for user '" + token + "' and tenant " + tenantId); } UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(token, tenantId); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); Authentication authResult = authenticationManager.authenticate(authRequest); if (info) { logger.info("Authentication success: " + authResult); } PaasManagerUser user = (PaasManagerUser) authResult.getPrincipal(); logger.info("User: " + user.getUsername()); logger.info("Token: " + user.getToken()); logger.info("Tenant: " + user.getTenantId()); logger.info("TenantName - Org: " + user.getTenantName()); SecurityContextHolder.getContext().setAuthentication(authResult); // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL"); rememberMeServices.loginSuccess(request, response, authResult); onSuccessfulAuthentication(request, response, authResult); } catch (AuthenticationException failed) { SecurityContextHolder.clearContext(); if (info) { logger.info("Authentication request for failed: " + failed); } rememberMeServices.loginFail(request, response); onUnsuccessfulAuthentication(request, response, failed); if (ignoreFailure) { chain.doFilter(request, response); } else { authenticationEntryPoint.commence(request, response, failed); } return; } response.addHeader("Www-Authenticate", "Keystone uri='" + keystoneURL + "'"); } // TODO jesuspg: question:add APIException chain.doFilter(request, response); }
From source file:com.mastercard.test.spring.security.SpringSecurityJUnit4ClassRunner.java
/** * Run the test corresponding to the child, which can be assumed to be an element * of the list returned by getChildren(). Ensures that relevant test events are * reported through the notifier.//w w w .j a v a 2 s.co m * * The implementation wraps the inherited runChild() method to insert the mock/test * user into the SecurityContext prior to execution and removes it after execution. * * @param frameworkMethod The method representing the child test. * @param notifier The notifier for the test execution. */ @SuppressWarnings("unchecked") @Override protected void runChild(FrameworkMethod frameworkMethod, RunNotifier notifier) { if (frameworkMethod instanceof AnnotationFrameworkMethod) { AnnotationFrameworkMethod annotationFrameworkMethod = (AnnotationFrameworkMethod) frameworkMethod; Annotation userAnnotation = annotationFrameworkMethod.getAnnotation(); WithSecurityContext withSecurityContext = userAnnotation.annotationType() .getAnnotation(WithSecurityContext.class); Class<? extends WithSecurityContextFactory<? extends Annotation>> clazz = withSecurityContext.factory(); WithSecurityContextFactory withSecurityContextFactory = buildWithSecurityContextFactory(clazz); SecurityContext securityContext = null; if (withSecurityContextFactory != null) { securityContext = withSecurityContextFactory.createSecurityContext(userAnnotation); } if (securityContext == null) { securityContext = SecurityContextHolder.createEmptyContext(); } SecurityContextHolder.setContext(securityContext); } super.runChild(frameworkMethod, notifier); SecurityContextHolder.clearContext(); }
From source file:com.mycompany.CRMFly.Security.AuthorityController.java
public void changeUserPassword() { changePasswordDao.changePassword(username, newPass); SecurityContextHolder.clearContext(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, " ? .", null)); }
From source file:com.telefonica.euro_iaas.sdc.rest.auth.OpenStackAuthenticationFilter.java
/** * (non-Javadoc) @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, * javax.servlet.FilterChain)./* w ww . ja va 2s . co m*/ */ public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final boolean debug = logger.isDebugEnabled(); final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; String header = request.getHeader(OPENSTACK_HEADER_TOKEN); String pathInfo = request.getPathInfo(); logger.debug(header); logger.debug(pathInfo); MDC.put("txId", ((HttpServletRequest) req).getSession().getId()); if (pathInfo != null && (pathInfo.equals("/") || pathInfo.equals("/extensions"))) { /** * It is not needed to authenticate these operations */ logger.debug("Operation does not need to Authenticate"); } else { if (header == null) { header = ""; } try { String token = header; if ("".equals(token)) { String str = "Missing token header"; logger.info(str); throw new BadCredentialsException(str); } String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID); String txId = request.getHeader("txId"); if (txId != null) { MDC.put("txId", txId); } logger.debug(tenantId); logger.debug(token); // String tenantId = request.getPathInfo().split("/")[3]; if (debug) { logger.debug("OpenStack Authentication Authorization header " + "found for user '" + token + "' and tenant " + tenantId); } UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(token, tenantId); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); Authentication authResult = authenticationManager.authenticate(authRequest); if (debug) { logger.debug("Authentication success: " + authResult); } // check AUTH-TOKEN and VDC are the same String uri = request.getRequestURI(); logger.debug("URI: " + uri); if (uri.contains("vdc") && !uri.contains(tenantId)) { String str = "Bad credentials for requested VDC"; logger.info(str); throw new AccessDeniedException(str); } UserDetails user = (UserDetails) authResult.getPrincipal(); logger.debug("User: " + user.getUsername()); logger.debug("Token: " + user.getPassword()); if (authResult.isAuthenticated()) { SecurityContextHolder.getContext().setAuthentication(authRequest); } // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL"); rememberMeServices.loginSuccess(request, response, authResult); onSuccessfulAuthentication(request, response, authResult); } catch (AuthenticationException failed) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication request for failed: " + failed); } rememberMeServices.loginFail(request, response); onUnsuccessfulAuthentication(request, response, failed); if (ignoreFailure) { chain.doFilter(request, response); } else { authenticationEntryPoint.commence(request, response, failed); } return; } catch (AccessDeniedException ex) { throw ex; } catch (Exception ex) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication exception: " + ex); } rememberMeServices.loginFail(request, response); if (ignoreFailure) { chain.doFilter(request, response); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } return; } String keystoneURL = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL); response.addHeader("Www-Authenticate", "Keystone uri='" + keystoneURL + "'"); } // TODO jesuspg: question:add APIException chain.doFilter(request, response); }
From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationFilter.java
/** * (non-Javadoc) @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, * javax.servlet.FilterChain).//from w w w . ja v a2 s .c om */ public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final boolean debug = logger.isDebugEnabled(); final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; String headerToken = request.getHeader(OPENSTACK_HEADER_TOKEN); String pathInfo = request.getPathInfo(); logger.debug(headerToken); logger.debug(pathInfo); // first of all, check HTTP if exists accept header if (!validateAcceptHeader(request, response)) { return; } MDC.put("txId", ((HttpServletRequest) req).getSession().getId()); if (pathInfo != null && (pathInfo.equals("/") || pathInfo.equals("/extensions"))) { /** * It is not needed to authenticate these operations */ logger.debug("Operation does not need to Authenticate"); } else { if (headerToken == null) { headerToken = ""; } try { String token = headerToken; if ("".equals(token)) { String str = "Missing token header"; logger.info(str); throw new BadCredentialsException(str); } String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID); logger.debug(tenantId); logger.debug(token); // String tenantId = request.getPathInfo().split("/")[3]; if (debug) { logger.debug("OpenStack Authentication Authorization header " + "found for user '" + token + "' and tenant " + tenantId); } UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(token, tenantId); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); Authentication authResult = authenticationManager.authenticate(authRequest); if (debug) { logger.debug("Authentication success: " + authResult); } // check AUTH-TOKEN and VDC are the same String uri = request.getRequestURI(); logger.debug("URI: " + uri); if (uri.contains("vdc") && !uri.contains(tenantId)) { String str = "Bad credentials for requested VDC"; logger.info(str); throw new AccessDeniedException(str); } UserDetails user = (UserDetails) authResult.getPrincipal(); logger.debug("User: " + user.getUsername()); logger.debug("Token: " + user.getPassword()); if (authResult.isAuthenticated()) { SecurityContextHolder.getContext().setAuthentication(authRequest); } // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL"); rememberMeServices.loginSuccess(request, response, authResult); onSuccessfulAuthentication(request, response, authResult); } catch (AuthenticationException failed) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication request for failed: " + failed); } rememberMeServices.loginFail(request, response); onUnsuccessfulAuthentication(request, response, failed); if (ignoreFailure) { chain.doFilter(request, response); } else { authenticationEntryPoint.commence(request, response, failed); } return; } catch (AccessDeniedException ex) { throw ex; } catch (Exception ex) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication exception: " + ex); } rememberMeServices.loginFail(request, response); if (ignoreFailure) { chain.doFilter(request, response); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } return; } String keystoneURL = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL); response.addHeader("Www-Authenticate", "Keystone uri='" + keystoneURL + "'"); } // TODO jesuspg: question:add APIException chain.doFilter(request, response); }
From source file:business.UploadTests.java
@Test(groups = "download", dependsOnGroups = "upload") public void downloadFiles() throws IOException { UserAuthenticationToken requester = getRequester(); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(requester); RequestRepresentation representation = requestController.getRequestById(requester, processInstanceId); log.info("Status: " + representation.getStatus()); log.info("Downloading..."); representation.getAttachments().forEach(f -> { printFile(f);/*from w w w . j a va2 s . com*/ HttpEntity<InputStreamResource> response = requestController.getFile(requester, representation.getProcessInstanceId(), f.getId()); log.info(String.format("Response: contenttype: [%s]", response.getHeaders().getContentType() == null ? null : response.getHeaders().getContentType().toString())); }); printFiles(representation.getAttachments()); SecurityContextHolder.clearContext(); }
From source file:de.blizzy.documentr.web.page.PageControllerTest.java
@Test public void getPageMustReturn304IfNotModified() throws IOException { when(session.getAttribute("authenticationCreationTime")).thenReturn( //$NON-NLS-1$ new GregorianCalendar(2012, Calendar.JUNE, 2).getTime().getTime()); when(request.getDateHeader("If-Modified-Since")).thenReturn( //$NON-NLS-1$ new GregorianCalendar(2012, Calendar.JUNE, 9).getTimeInMillis()); when(request.getSession()).thenReturn(session); when(pageStore.getPageMetadata(eq(PROJECT), eq(BRANCH), eq("nonexistent"))) //$NON-NLS-1$ .thenReturn(new PageMetadata("user", new GregorianCalendar(2012, Calendar.JUNE, 1).getTime(), 123, //$NON-NLS-1$ "commit")); //$NON-NLS-1$ TestPageUtil.clearProjectEditTimes(); SecurityContextHolder.setContext(createSecurityContext(anonymousAuthentication)); String view = pageController.getPage(PROJECT, BRANCH, "nonexistent", model, request, response); //$NON-NLS-1$ SecurityContextHolder.clearContext(); assertTrue(removeViewPrefix(view).startsWith("/error/" + HttpServletResponse.SC_NOT_MODIFIED + "/")); //$NON-NLS-1$ //$NON-NLS-2$ assertForward(view);//from w w w . j a v a 2s . co m }