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:com.evolveum.midpoint.model.test.AbstractModelIntegrationTest.java

protected void assertNotAuthorized(MidPointPrincipal principal, String action, AuthorizationPhaseType phase)
        throws SchemaException {
    SecurityContext origContext = SecurityContextHolder.getContext();
    createSecurityContext(principal);/* w ww  . j  a v a  2 s. c  o m*/
    boolean isAuthorized = securityEnforcer.isAuthorized(action, phase, null, null, null, null);
    SecurityContextHolder.setContext(origContext);
    assertFalse("AuthorizationEvaluator.isAuthorized: Principal " + principal + " IS authorized for action "
            + action + " (" + phase + ") but he should not be", isAuthorized);
}

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

protected void createSecurityContext(MidPointPrincipal principal) {
    SecurityContext context = new SecurityContextImpl();
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null);
    context.setAuthentication(authentication);
    SecurityContextHolder.setContext(context);
}

From source file:org.apache.rave.portal.service.impl.DefaultUserService.java

@Override
public void setAuthenticatedUser(String userId) {
    final User user = userRepository.get(userId);
    if (user == null) {
        throw new UsernameNotFoundException("User with id '" + userId + "' was not found!");
    }/*from   www .  j  a v a  2 s  . c om*/
    SecurityContext securityContext = createContext(user);
    SecurityContextHolder.setContext(securityContext);
}

From source file:org.apache.syncope.core.spring.security.AuthContextUtils.java

public static <T> T execWithAuthContext(final String domainKey, final Executable<T> executable) {
    SecurityContext ctx = SecurityContextHolder.getContext();
    setFakeAuth(domainKey);/*from  w w  w.j ava  2 s .c o m*/
    try {
        return executable.exec();
    } catch (Throwable t) {
        LOG.debug("Error during execution with domain {} context", domainKey, t);
        throw t;
    } finally {
        SecurityContextHolder.clearContext();
        SecurityContextHolder.setContext(ctx);
    }
}

From source file:org.asqatasun.webapp.controller.PageListControllerTest.java

/**
 * /*  w w w . jav  a2s  . 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();
    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.broadleafcommerce.common.web.resource.BroadleafResourceHttpRequestHandler.java

protected void establishThinRequestContext() {
    BroadleafRequestContext oldBrc = BroadleafRequestContext.getBroadleafRequestContext();
    if (oldBrc == null || oldBrc.getSite() == null || oldBrc.getTheme() == null) {
        // Resolving sites and sandboxes is often dependent on having a security context present in the request.
        // For example, resolving a sandbox requires the current user to have the BLC_ADMIN_USER in his Authentication.
        // For performance reasons, we do not go through the entire Spring Security filter chain on requests
        // for resources like JavaScript and CSS files. However, when theming is enabled, we potentially have to
        // resolve a specific version of the theme for a sandbox so that we can replace variables appropriately. This
        // then depends on the sandbox being resolved, which requires the Authentication object to be present.
        // We will grab the Authentication object associated with this user's session and set it on the
        // SecurityContextHolder since Spring Security will be bypassed.
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();/* www.ja v a  2s.  c  o  m*/
        HttpSession session = req.getSession(false);
        SecurityContext ctx = readSecurityContextFromSession(session);
        if (ctx != null) {
            SecurityContextHolder.setContext(ctx);
        }

        BroadleafRequestContext newBrc = new BroadleafRequestContext();
        if (!isGlobalAdmin(req)) {
            ServletWebRequest swr = new ServletWebRequest(req);
            newBrc.setSite(siteResolver.resolveSite(swr, true));
            newBrc.setSandBox(sbResolver.resolveSandBox(swr, newBrc.getSite()));
            BroadleafRequestContext.setBroadleafRequestContext(newBrc);
            newBrc.setTheme(themeResolver.resolveTheme(swr));
        }
    }
}

From source file:org.eclipse.hawkbit.amqp.AmqpMessageHandlerService.java

/**
 * * Executed if a amqp message arrives.
 * //from   w w  w  .  j  a  v  a2 s .  co m
 * @param message
 *            the message
 * @param type
 *            the type
 * @param tenant
 *            the tenant
 * @param virtualHost
 *            the virtual host
 * @return the rpc message back to supplier.
 */
public Message onMessage(final Message message, final String type, final String tenant,
        final String virtualHost) {
    checkContentTypeJson(message);
    final SecurityContext oldContext = SecurityContextHolder.getContext();
    try {
        final MessageType messageType = MessageType.valueOf(type);
        switch (messageType) {
        case THING_CREATED:
            setTenantSecurityContext(tenant);
            registerTarget(message, virtualHost);
            break;
        case EVENT:
            setTenantSecurityContext(tenant);
            final String topicValue = getStringHeaderKey(message, MessageHeaderKey.TOPIC, "EventTopic is null");
            final EventTopic eventTopic = EventTopic.valueOf(topicValue);
            handleIncomingEvent(message, eventTopic);
            break;
        default:
            logAndThrowMessageError(message, "No handle method was found for the given message type.");
        }
    } catch (final IllegalArgumentException ex) {
        throw new AmqpRejectAndDontRequeueException("Invalid message!", ex);
    } finally {
        SecurityContextHolder.setContext(oldContext);
    }
    return null;
}

From source file:org.eclipse.hawkbit.amqp.AmqpMessageHandlerService.java

private static void setSecurityContext(final Authentication authentication) {
    final SecurityContextImpl securityContextImpl = new SecurityContextImpl();
    securityContextImpl.setAuthentication(authentication);
    SecurityContextHolder.setContext(securityContextImpl);
}

From source file:org.geoserver.importer.rest.ImportTaskControllerTest.java

private void doLogin() throws Exception {
    SecurityContextHolder.setContext(new SecurityContextImpl());
    List<GrantedAuthority> l = new ArrayList<GrantedAuthority>();
    l.add(new GeoServerRole("ROLE_ADMINISTRATOR"));
    SecurityContextHolder.getContext()//ww  w . j  a  va 2s  .  c  o  m
            .setAuthentication(new UsernamePasswordAuthenticationToken("admin", "geoserver", l));
}

From source file:org.geoserver.test.GeoServerSystemTestSupport.java

/**
 * Sets up the authentication context for the test.
 * <p>/* w w w .  j  a va 2s  .  c  o  m*/
 * This context lasts only for a single test case, it is cleared after every test has completed. 
 * </p>
 * @param username The username.
 * @param password The password.
 * @param roles Roles to assign.
 */
protected void login(String username, String password, String... roles) {
    SecurityContextHolder.setContext(new SecurityContextImpl());
    List<GrantedAuthority> l = new ArrayList<GrantedAuthority>();
    for (String role : roles) {
        l.add(new GrantedAuthorityImpl(role));
    }

    SecurityContextHolder.getContext()
            .setAuthentication(new UsernamePasswordAuthenticationToken(username, password, l));
}