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

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

Introduction

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

Prototype

public static SecurityContext createEmptyContext() 

Source Link

Document

Delegates the creation of a new, empty context to the configured strategy.

Usage

From source file:cn.org.once.cstack.security.SecurityTestIT.java

@Before
public void setup() {
    logger.info("*********************************");
    logger.info("             setup               ");
    logger.info("*********************************");

    this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();

    // If user1 is null (first test) we create its session and its application
    try {// www.ja v  a 2 s .  co m
        logger.info("Create session for user1 : " + user1);
        // we affect the user to skip this branch too
        User user1 = userService.findByLogin("usertest1");
        Authentication authentication = new UsernamePasswordAuthenticationToken(user1.getLogin(),
                user1.getPassword());
        Authentication result = authenticationManager.authenticate(authentication);
        SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
        securityContext.setAuthentication(result);
        session1 = new MockHttpSession();
        session1.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                securityContext);
    } catch (ServiceException e) {
        logger.error(e.getLocalizedMessage());
    }

    // After the first tests, all others are for User2
    try {
        logger.info("Create session for user2");
        User user2 = userService.findByLogin("usertest2");
        Authentication authentication = new UsernamePasswordAuthenticationToken(user2.getLogin(),
                user2.getPassword());
        Authentication result = authenticationManager.authenticate(authentication);
        SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
        securityContext.setAuthentication(result);
        session2 = new MockHttpSession();
        session2.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                securityContext);
    } catch (ServiceException e) {
        logger.error(e.getLocalizedMessage());
    }

}

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.//from  w  w  w. j av a2  s.  c o  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:org.jasig.springframework.security.portlet.context.PortletSessionSecurityContextRepositoryTests.java

@Test
public void contextIsRemovedFromSessionIfCurrentContextIsAnonymous() throws Exception {
    PortletSessionSecurityContextRepository repo = new PortletSessionSecurityContextRepository();
    MockPortletRequest request = new MockPortletRequest();
    SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
    ctxInSession.setAuthentication(testToken);
    request.getPortletSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession,
            PortletSession.APPLICATION_SCOPE);
    PortletRequestResponseHolder holder = new PortletRequestResponseHolder(request, new MockPortletResponse());
    repo.loadContext(holder);/*  w ww  .  j a v  a2s  . c  o  m*/
    SecurityContextHolder.getContext()
            .setAuthentication(new AnonymousAuthenticationToken("x", "x", testToken.getAuthorities()));
    repo.saveContext(SecurityContextHolder.getContext(), holder);
    assertNull(request.getPortletSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY,
            PortletSession.APPLICATION_SCOPE));
}

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());
    }/*from   w  w  w . j a va2  s  . c  o 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:org.jasig.springframework.security.portlet.context.PortletSessionSecurityContextRepositoryTests.java

@Test
public void contextIsRemovedFromSessionIfCurrentContextIsEmpty() throws Exception {
    PortletSessionSecurityContextRepository repo = new PortletSessionSecurityContextRepository();
    repo.setSpringSecurityContextKey("imTheContext");
    MockPortletRequest request = new MockPortletRequest();
    SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
    ctxInSession.setAuthentication(testToken);
    request.getPortletSession().setAttribute("imTheContext", ctxInSession, PortletSession.APPLICATION_SCOPE);
    PortletRequestResponseHolder holder = new PortletRequestResponseHolder(request, new MockPortletResponse());
    repo.loadContext(holder);//from www . jav  a2 s  . c  o m
    // Save an empty context
    repo.saveContext(SecurityContextHolder.getContext(), holder);
    assertNull(request.getPortletSession().getAttribute("imTheContext", PortletSession.APPLICATION_SCOPE));
}

From source file:org.carewebframework.security.spring.DesktopSecurityContextRepository.java

/**
 * By default, calls {@link SecurityContextHolder#createEmptyContext()} to obtain a new context
 * (there should be no context present in the holder when this method is called). Using this
 * approach the context creation strategy is decided by the
 * {@link SecurityContextHolderStrategy} in use. The default implementations will return a new
 * <tt>SecurityContextImpl</tt>.
 * <p>//from ww w  .ja  v  a 2  s. c o m
 * An alternative way of customizing the <tt>SecurityContext</tt> implementation is by setting
 * the <tt>securityContextClass</tt> property. In this case, the method will attempt to invoke
 * the no-args constructor on the supplied class instead and return the created instance.
 * 
 * @return a new SecurityContext instance. Never null.
 */
private SecurityContext generateNewContext() {
    return SecurityContextHolder.createEmptyContext();
}

From source file:org.jasig.springframework.security.portlet.context.PortletSessionSecurityContextRepository.java

/**
 * By default, calls {@link SecurityContextHolder#createEmptyContext()} to obtain a new context (there should be
 * no context present in the holder when this method is called). Using this approach the context creation
 * strategy is decided by the {@link SecurityContextHolderStrategy} in use. The default implementations
 * will return a new <tt>SecurityContextImpl</tt>.
 *
 * @return a new SecurityContext instance. Never null.
 *///from   ww w.ja  v  a  2 s. c o m
protected SecurityContext generateNewContext() {
    return SecurityContextHolder.createEmptyContext();
}

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());
    }/*from w w  w  . j a  va2 s  .c om*/

    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.extensions.portlet.PortletSessionContextIntegrationInterceptor.java

/**
 * Creates a new <code>SecurityContext</code> object.  The specific class is
 * determined by the setting of the {@link #contextClass} property.
 * @return the new <code>SecurityContext</code>
 * @throws PortletException if the creation throws an <code>InstantiationException</code> or
 *     an <code>IllegalAccessException</code>, then this method will wrap them in a
 *     <code>PortletException</code>
 */// w w w  . j  ava2s.  co  m
SecurityContext generateNewContext() throws PortletException {
    if (contextClass == null) {
        return SecurityContextHolder.createEmptyContext();
    }

    try {
        return this.contextClass.newInstance();
    } catch (InstantiationException ie) {
        throw new PortletException(ie);
    } catch (IllegalAccessException iae) {
        throw new PortletException(iae);
    }
}

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;/*from   w ww  . ja v  a 2  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);
}