Example usage for org.springframework.security.core.context SecurityContextHolder setContext

List of usage examples for org.springframework.security.core.context SecurityContextHolder setContext

Introduction

In this page you can find the example usage for org.springframework.security.core.context SecurityContextHolder setContext.

Prototype

public static void setContext(SecurityContext context) 

Source Link

Document

Associates a new SecurityContext with the current thread of execution.

Usage

From source file:springacltutorial.infrastructure.MyMethodSecurityInterceptor.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  w  w  .  j a  v a  2  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 to run as a different user
    Authentication runAs = this.runAsManager.buildRunAs(authenticated, object, attributes);
    if (runAs != null) {
        authenticated = runAs;
    }

    // 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));
    }

    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:springacltutorial.infrastructure.MyMethodSecurityInterceptor.java

/**
 * Completes the work of the <tt>AbstractSecurityInterceptor</tt> after the
 * secure object invocation has been completed.
 * /*from   ww w . j  av  a 2s .com*/
 * @param token
 *            as returned by the {@link #beforeInvocation(Object)} method
 * @param returnedObject
 *            any object returned from the secure object invocation (may be
 *            <tt>null</tt>)
 * @return the object the secure object invocation should ultimately return
 *         to its caller (may be <tt>null</tt>)
 */
protected Object afterInvocation(InterceptorStatusToken token, Object returnedObject) {
    if (token == null) {
        // public object
        return returnedObject;
    }

    if (token.isContextHolderRefreshRequired()) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Reverting to original Authentication: " + token.getSecurityContext().getAuthentication());
        }

        SecurityContextHolder.setContext(token.getSecurityContext());
    }

    if (afterInvocationManager != null) {
        // Attempt after invocation handling
        try {
            returnedObject = afterInvocationManager.decide(token.getSecurityContext().getAuthentication(),
                    token.getSecureObject(), token.getAttributes(), returnedObject);
        } catch (AccessDeniedException accessDeniedException) {
            AuthorizationFailureEvent event = new AuthorizationFailureEvent(token.getSecureObject(),
                    token.getAttributes(), token.getSecurityContext().getAuthentication(),
                    accessDeniedException);
            publishEvent(event);

            throw accessDeniedException;
        }
    }

    return returnedObject;
}

From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationProviderTest.java

@Test
public void shouldAddCredentialsToClaudiaDataWhenAuthenticatedWithToken() {
    // given// w w w  .  j  a v  a2  s  . c  om

    ClaudiaData claudiaData = new ClaudiaData("org", "vdc", "service");
    SecurityContext context = mock(SecurityContext.class);
    SecurityContextHolder.setContext(context);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = mock(
            UsernamePasswordAuthenticationToken.class);
    when(context.getAuthentication()).thenReturn(usernamePasswordAuthenticationToken);
    when(usernamePasswordAuthenticationToken.getPrincipal()).thenReturn("token1");
    when(usernamePasswordAuthenticationToken.getCredentials()).thenReturn("tenantId1");
    // when
    OpenStackAuthenticationProvider.addCredentialsToClaudiaData(claudiaData);

    // then
    assertNotNull(claudiaData);
    assertEquals("org", claudiaData.getOrg());
    assertEquals("vdc", claudiaData.getVdc());
    assertEquals("service", claudiaData.getService());
    assertEquals("token1", claudiaData.getUser().getToken());
    assertEquals("tenantId1", claudiaData.getUser().getTenantId());
    assertEquals("", claudiaData.getUser().getTenantName());

}

From source file:org.orcid.api.t2.server.delegator.T2OrcidApiServiceVersionedDelegatorTest.java

private void setUpSecurityContext(String userOrcid) {
    SecurityContextImpl securityContext = new SecurityContextImpl();
    OrcidOAuth2Authentication mockedAuthentication = mock(OrcidOAuth2Authentication.class);
    securityContext.setAuthentication(mockedAuthentication);
    SecurityContextHolder.setContext(securityContext);
    when(mockedAuthentication.getPrincipal()).thenReturn(new ProfileEntity(userOrcid));
    Set<String> scopes = new HashSet<String>();
    scopes.add(ScopePathType.ACTIVITIES_UPDATE.value());
    scopes.add(ScopePathType.READ_LIMITED.value());
    OAuth2Request authorizationRequest = new OAuth2Request(Collections.<String, String>emptyMap(), userOrcid,
            Collections.<GrantedAuthority>emptyList(), true, scopes, Collections.<String>emptySet(), null,
            Collections.<String>emptySet(), Collections.<String, Serializable>emptyMap());
    when(mockedAuthentication.getOAuth2Request()).thenReturn(authorizationRequest);
}

From source file:org.orcid.api.t2.server.delegator.T2OrcidApiServiceVersionedDelegatorTest.java

private void setUpSecurityContextForClientOnly(String clientId, Set<String> scopes) {
    SecurityContextImpl securityContext = new SecurityContextImpl();
    OrcidOAuth2Authentication mockedAuthentication = mock(OrcidOAuth2Authentication.class);
    securityContext.setAuthentication(mockedAuthentication);
    SecurityContextHolder.setContext(securityContext);
    when(mockedAuthentication.getPrincipal()).thenReturn(new ProfileEntity(clientId));
    when(mockedAuthentication.isClientOnly()).thenReturn(true);
    OAuth2Request authorizationRequest = new OAuth2Request(Collections.<String, String>emptyMap(), clientId,
            Collections.<GrantedAuthority>emptyList(), true, scopes, Collections.<String>emptySet(), null,
            Collections.<String>emptySet(), Collections.<String, Serializable>emptyMap());
    when(mockedAuthentication.getOAuth2Request()).thenReturn(authorizationRequest);
}

From source file:architecture.ee.web.community.spring.controller.SocialConnectController.java

private void createSecurityContext(User userToUse, HttpServletRequest request) {
    if (userToUse.getUserId() > 0) {
        UserDetails details = userDetailsService.loadUserByUsername(userToUse.getUsername());
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(details,
                null, details.getAuthorities());
        SecurityContextImpl context = new SecurityContextImpl();
        context.setAuthentication(authentication);
        SecurityContextHolder.setContext(context);
        HttpSession httpsession = request.getSession(true);
        httpsession.setAttribute("SPRING_SECURITY_CONTEXT", context);
    }/*from   w w w .  j  a  v a  2s  . c  o m*/
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils.java

/**
 * Execute a closure with the current authentication. Assumes that there's an authentication in the
 * http session and that the closure is running in a separate thread from the web request, so the
 * context and authentication aren't available to the standard ThreadLocal.
 *
 * @param closure the code to run//  w  w  w  .j  a  v  a2  s  .c o m
 * @return the closure's return value
 */
public static Object doWithAuth(@SuppressWarnings("rawtypes") final Closure closure) {
    boolean set = false;
    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        HttpSession httpSession = SecurityRequestHolder.getRequest().getSession(false);
        SecurityContext context = null;
        if (httpSession != null) {
            context = (SecurityContext) httpSession
                    .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
            if (context != null) {
                SecurityContextHolder.setContext(context);
                set = true;
            }
        }
    }

    try {
        return closure.call();
    } finally {
        if (set) {
            SecurityContextHolder.clearContext();
        }
    }
}

From source file:grails.plugin.springsecurity.SpringSecurityUtils.java

/**
 * Execute a closure with the current authentication. Assumes that there's an authentication in the
 * http session and that the closure is running in a separate thread from the web request, so the
 * context and authentication aren't available to the standard ThreadLocal.
 *
 * @param closure the code to run/*from w  w w.ja  v a 2 s .c o m*/
 * @return the closure's return value
 */
public static Object doWithAuth(@SuppressWarnings("rawtypes") final Closure closure) {
    boolean set = false;
    if (SecurityContextHolder.getContext().getAuthentication() == null
            && SecurityRequestHolder.getRequest() != null) {
        HttpSession httpSession = SecurityRequestHolder.getRequest().getSession(false);
        SecurityContext securityContext = null;
        if (httpSession != null) {
            securityContext = (SecurityContext) httpSession
                    .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
            if (securityContext != null) {
                SecurityContextHolder.setContext(securityContext);
                set = true;
            }
        }
    }

    try {
        return closure.call();
    } finally {
        if (set) {
            SecurityContextHolder.clearContext();
        }
    }
}

From source file:com.evolveum.midpoint.model.test.AbstractModelIntegrationTest.java

protected void assertAuthorized(MidPointPrincipal principal, String action, AuthorizationPhaseType phase)
        throws SchemaException {
    SecurityContext origContext = SecurityContextHolder.getContext();
    createSecurityContext(principal);//from  w  ww .  ja  v a 2s.co  m
    try {
        assertTrue("AuthorizationEvaluator.isAuthorized: Principal " + principal + " NOT authorized for action "
                + action, securityEnforcer.isAuthorized(action, phase, null, null, null, null));
        if (phase == null) {
            securityEnforcer.decide(SecurityContextHolder.getContext().getAuthentication(),
                    createSecureObject(), createConfigAttributes(action));
        }
    } finally {
        SecurityContextHolder.setContext(origContext);
    }
}