List of usage examples for org.springframework.security.core.context SecurityContextHolder setContext
public static void setContext(SecurityContext context)
SecurityContext
with the current thread of execution. From source file:org.mifos.security.AuthenticationAuthorizationServiceFacadeImpl.java
@Override public void reloadUserDetailsForSecurityContext(String username) { UserDetails userSecurityDetails = loadUserByUsername(username); MifosUser reloadedUserDetails = (MifosUser) userSecurityDetails; SecurityContext securityContext = SecurityContextHolder.getContext(); if (securityContext == null) { securityContext = new SecurityContextImpl(); SecurityContextHolder.setContext(securityContext); }//from ww w. j av a2 s . c o m Authentication authentication = new UsernamePasswordAuthenticationToken(reloadedUserDetails, reloadedUserDetails, reloadedUserDetails.getAuthorities()); securityContext.setAuthentication(authentication); }
From source file:org.opens.tgol.controller.PageListControllerTest.java
/** * /*ww w .j a v a 2 s .co m*/ */ private void setUpMockAuthenticationContext() { // initialise the context with the user identified by the email // "test1@test.com" seen as authenticated Collection<GrantedAuthority> gac = new ArrayList<GrantedAuthority>(); TgolUserDetails tud = new TgolUserDetails("test1@test.com", "", true, false, true, true, gac, mockUser); mockAuthentication = createMock(Authentication.class); SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(mockAuthentication); SecurityContextHolder.setContext(securityContextImpl); expect(mockAuthentication.getName()).andReturn("test1@test.com").anyTimes(); expect(mockAuthentication.getPrincipal()).andReturn(tud).anyTimes(); expect(mockAuthentication.getAuthorities()).andReturn(null).anyTimes(); replay(mockAuthentication); mockAuthenticationDetails = createMock(AuthenticationDetails.class); expect(mockAuthenticationDetails.getContext()).andReturn("test1@test.com").anyTimes(); replay(mockAuthenticationDetails); }
From source file:org.slc.sli.api.service.BasicServiceTest.java
private void setPrincipalInContext(SLIPrincipal principal) { Authentication authentication = Mockito.mock(Authentication.class); Mockito.when(authentication.getPrincipal()).thenReturn(principal); SecurityContext context = Mockito.mock(SecurityContext.class); Mockito.when(context.getAuthentication()).thenReturn(authentication); SecurityContextHolder.setContext(context); }
From source file:org.slc.sli.api.service.BasicServiceTest.java
@AfterClass public static void reset() { // Let's be good citizens and clean up after ourselves for the subsequent tests! SecurityUtil.setUserContext(prevUserContext); SecurityContextHolder.setContext(prevSecurityContext); }
From source file:org.springframework.security.access.intercept.AbstractSecurityInterceptor.java
protected InterceptorStatusToken beforeInvocation(Object object) { Assert.notNull(object, "Object was null"); final boolean debug = logger.isDebugEnabled(); if (!getSecureObjectClass().isAssignableFrom(object.getClass())) { throw new IllegalArgumentException( "Security invocation attempted for object " + object.getClass().getName() + " but AbstractSecurityInterceptor only configured to support secure objects of type: " + getSecureObjectClass()); }/* w ww.j a va2 s.co m*/ Collection<ConfigAttribute> attributes = this.obtainSecurityMetadataSource().getAttributes(object); if (attributes == null || attributes.isEmpty()) { if (rejectPublicInvocations) { throw new IllegalArgumentException("Secure object invocation " + object + " was denied as public invocations are not allowed via this interceptor. " + "This indicates a configuration error because the " + "rejectPublicInvocations property is set to 'true'"); } if (debug) { logger.debug("Public object - authentication not attempted"); } publishEvent(new PublicInvocationEvent(object)); return null; // no further work post-invocation } if (debug) { logger.debug("Secure object: " + object + "; Attributes: " + attributes); } if (SecurityContextHolder.getContext().getAuthentication() == null) { credentialsNotFound(messages.getMessage("AbstractSecurityInterceptor.authenticationNotFound", "An Authentication object was not found in the SecurityContext"), object, attributes); } Authentication authenticated = authenticateIfRequired(); // Attempt authorization try { this.accessDecisionManager.decide(authenticated, object, attributes); } catch (AccessDeniedException accessDeniedException) { publishEvent(new AuthorizationFailureEvent(object, attributes, authenticated, accessDeniedException)); throw accessDeniedException; } if (debug) { logger.debug("Authorization successful"); } if (publishAuthorizationSuccess) { publishEvent(new AuthorizedEvent(object, attributes, authenticated)); } // Attempt to run as a different user Authentication runAs = this.runAsManager.buildRunAs(authenticated, object, attributes); if (runAs == null) { if (debug) { logger.debug("RunAsManager did not change Authentication object"); } // no further work post-invocation return new InterceptorStatusToken(SecurityContextHolder.getContext(), false, attributes, object); } else { if (debug) { logger.debug("Switching to RunAs Authentication: " + runAs); } SecurityContext origCtx = SecurityContextHolder.getContext(); SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); SecurityContextHolder.getContext().setAuthentication(runAs); // need to revert to token.Authenticated post-invocation return new InterceptorStatusToken(origCtx, true, attributes, object); } }
From source file:org.springframework.security.access.intercept.AbstractSecurityInterceptor.java
/** * Cleans up the work of the <tt>AbstractSecurityInterceptor</tt> after the secure * object invocation has been completed. This method should be invoked after the * secure object invocation and before afterInvocation regardless of the secure object * invocation returning successfully (i.e. it should be done in a finally block). * * @param token as returned by the {@link #beforeInvocation(Object)} method *//*from ww w. j a v a2 s . com*/ protected void finallyInvocation(InterceptorStatusToken token) { if (token != null && token.isContextHolderRefreshRequired()) { if (logger.isDebugEnabled()) { logger.debug( "Reverting to original Authentication: " + token.getSecurityContext().getAuthentication()); } SecurityContextHolder.setContext(token.getSecurityContext()); } }
From source file:org.springframework.security.extensions.portlet.PortletSessionContextIntegrationInterceptor.java
private boolean preHandle(PortletRequest request, PortletResponse response, Object handler) throws Exception { PortletSession portletSession = null; boolean portletSessionExistedAtStartOfRequest = false; // see if the portlet session already exists (or should be eagerly created) try {//from www . j av a 2 s. c o m portletSession = request.getPortletSession(forceEagerSessionCreation); } catch (IllegalStateException ignored) { } // if there is a session, then see if there is a contextClass to bring in if (portletSession != null) { // remember that the session already existed portletSessionExistedAtStartOfRequest = true; // attempt to retrieve the contextClass from the session Object contextFromSessionObject = portletSession.getAttribute(SPRING_SECURITY_CONTEXT_KEY, portletSessionScope()); // if we got a contextClass then place it into the holder if (contextFromSessionObject != null) { // if we are supposed to clone it, then do so if (cloneFromPortletSession) { Assert.isInstanceOf(Cloneable.class, contextFromSessionObject, "Context must implement Clonable and provide a Object.clone() method"); try { Method m = contextFromSessionObject.getClass().getMethod("clone", new Class[] {}); if (!m.isAccessible()) { m.setAccessible(true); } contextFromSessionObject = m.invoke(contextFromSessionObject, new Object[] {}); } catch (Exception ex) { ReflectionUtils.handleReflectionException(ex); } } // if what we got is a valid contextClass then place it into the holder, otherwise create a new one if (contextFromSessionObject instanceof SecurityContext) { if (logger.isDebugEnabled()) logger.debug("Obtained from SPRING_SECURITY_CONTEXT a valid SecurityContext and " + "set to SecurityContextHolder: '" + contextFromSessionObject + "'"); SecurityContextHolder.setContext((SecurityContext) contextFromSessionObject); } else { if (logger.isWarnEnabled()) logger.warn("SPRING_SECURITY_CONTEXT did not contain a SecurityContext but contained: '" + contextFromSessionObject + "'; are you improperly modifying the PortletSession directly " + "(you should always use SecurityContextHolder) or using the PortletSession attribute " + "reserved for this class? - new SecurityContext instance associated with " + "SecurityContextHolder"); SecurityContextHolder.setContext(generateNewContext()); } } else { // there was no contextClass in the session, so create a new contextClass and put it in the holder if (logger.isDebugEnabled()) logger.debug("PortletSession returned null object for SPRING_SECURITY_CONTEXT - new " + "SecurityContext instance associated with SecurityContextHolder"); SecurityContextHolder.setContext(generateNewContext()); } } else { // there was no session, so create a new contextClass and place it in the holder if (logger.isDebugEnabled()) logger.debug("No PortletSession currently exists - new SecurityContext instance " + "associated with SecurityContextHolder"); SecurityContextHolder.setContext(generateNewContext()); } // place attributes onto the request to remember if the session existed and the hashcode of the contextClass request.setAttribute(SESSION_EXISTED, new Boolean(portletSessionExistedAtStartOfRequest)); request.setAttribute(CONTEXT_HASHCODE, new Integer(SecurityContextHolder.getContext().hashCode())); return true; }
From source file:org.springframework.security.web.authentication.www.DigestAuthenticationFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String header = request.getHeader("Authorization"); if (header == null || !header.startsWith("Digest ")) { chain.doFilter(request, response); return;/* w w w.j a v a2 s . c om*/ } if (logger.isDebugEnabled()) { logger.debug("Digest Authorization header received from user agent: " + header); } DigestData digestAuth = new DigestData(header); try { digestAuth.validateAndDecode(this.authenticationEntryPoint.getKey(), this.authenticationEntryPoint.getRealmName()); } catch (BadCredentialsException e) { fail(request, response, e); return; } // Lookup password for presented username // NB: DAO-provided password MUST be clear text - not encoded/salted // (unless this instance's passwordAlreadyEncoded property is 'false') boolean cacheWasUsed = true; UserDetails user = this.userCache.getUserFromCache(digestAuth.getUsername()); String serverDigestMd5; try { if (user == null) { cacheWasUsed = false; user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername()); if (user == null) { throw new AuthenticationServiceException( "AuthenticationDao returned null, which is an interface contract violation"); } this.userCache.putUserInCache(user); } serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod()); // If digest is incorrect, try refreshing from backend and recomputing if (!serverDigestMd5.equals(digestAuth.getResponse()) && cacheWasUsed) { if (logger.isDebugEnabled()) { logger.debug( "Digest comparison failure; trying to refresh user from DAO in case password had changed"); } user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername()); this.userCache.putUserInCache(user); serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod()); } } catch (UsernameNotFoundException notFound) { fail(request, response, new BadCredentialsException( this.messages.getMessage("DigestAuthenticationFilter.usernameNotFound", new Object[] { digestAuth.getUsername() }, "Username {0} not found"))); return; } // If digest is still incorrect, definitely reject authentication attempt if (!serverDigestMd5.equals(digestAuth.getResponse())) { if (logger.isDebugEnabled()) { logger.debug("Expected response: '" + serverDigestMd5 + "' but received: '" + digestAuth.getResponse() + "'; is AuthenticationDao returning clear text passwords?"); } fail(request, response, new BadCredentialsException(this.messages .getMessage("DigestAuthenticationFilter.incorrectResponse", "Incorrect response"))); return; } // To get this far, the digest must have been valid // Check the nonce has not expired // We do this last so we can direct the user agent its nonce is stale // but the request was otherwise appearing to be valid if (digestAuth.isNonceExpired()) { fail(request, response, new NonceExpiredException(this.messages .getMessage("DigestAuthenticationFilter.nonceExpired", "Nonce has expired/timed out"))); return; } if (logger.isDebugEnabled()) { logger.debug("Authentication success for user: '" + digestAuth.getUsername() + "' with response: '" + digestAuth.getResponse() + "'"); } Authentication authentication = createSuccessfulAuthentication(request, user); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); SecurityContextHolder.setContext(context); chain.doFilter(request, response); }
From source file:org.springframework.security.web.authentication.www.DigestAuthenticationFilterTests.java
@Test public void authenticationCreatesEmptyContext() throws Exception { SecurityContext existingContext = SecurityContextHolder.createEmptyContext(); TestingAuthenticationToken existingAuthentication = new TestingAuthenticationToken("existingauthenitcated", "pass", "ROLE_USER"); existingContext.setAuthentication(existingAuthentication); SecurityContextHolder.setContext(existingContext); String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);// w ww .ja va2s .com request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); filter.setCreateAuthenticatedToken(true); executeFilterInContainerSimulator(filter, request, true); assertThat(existingAuthentication).isSameAs(existingContext.getAuthentication()); }
From source file:org.unitedinternet.cosmo.acegisecurity.context.HttpRequestContextIntegrationFilter.java
/** * Generates a new security context, continues the filter chain, * then clears the context by generating another new one. * * @param request the servlet request/* w w w .ja v a2 s . c o m*/ * @param response the servlet response * @param chain the filter chain * @throws IOException if an I/O error occurs * @throws ServletException if any other error occurs */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request.getAttribute(FILTER_APPLIED) != null) { // ensure that filter is applied only once per request chain.doFilter(request, response); return; } request.setAttribute(FILTER_APPLIED, Boolean.TRUE); if (LOG.isDebugEnabled()) { LOG.debug("New SecurityContext instance associated with SecurityContextHolder"); } SecurityContextHolder.setContext(generateNewContext()); try { chain.doFilter(request, response); } catch (IOException ioe) { throw ioe; } catch (ServletException se) { throw se; } finally { // do clean up, even if there was an exception SecurityContextHolder.clearContext(); if (LOG.isDebugEnabled()) { LOG.debug("SecurityContextHolder refreshed, as request processing completed"); } } }