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:org.vaadin.spring.security.managed.SecurityContextVaadinRequestListener.java

@Override
public void onRequestStart(VaadinRequest request, VaadinResponse response) {
    final WrappedSession wrappedSession = request.getWrappedSession(false);
    VaadinSession session = null;//from   w  w w . j a  v a 2 s.  co  m
    if (wrappedSession != null) {
        session = VaadinSession.getForSession(request.getService(), wrappedSession);
    }

    SecurityContextHolder.clearContext();
    if (session != null) {
        logger.trace("Loading security context from VaadinSession {}", session);
        SecurityContext securityContext;
        session.lock();
        try {
            securityContext = (SecurityContext) session.getAttribute(SECURITY_CONTEXT_SESSION_ATTRIBUTE);
        } finally {
            session.unlock();
        }
        if (securityContext == null) {
            logger.trace("No security context found in VaadinSession {}", session);
        } else {
            logger.trace("Setting security context to {}", securityContext);
            SecurityContextHolder.setContext(securityContext);
        }
    } else {
        logger.trace("No VaadinSession available for retrieving the security context");
    }
}

From source file:org.vaadin.spring.security.internal.SecurityContextVaadinRequestListener.java

@Override
public void onRequestStart(VaadinRequest request, VaadinResponse response) {
    final WrappedSession wrappedSession = request.getWrappedSession(false);
    VaadinSession session = null;/*from   w  ww.  j  a v  a  2  s.  co  m*/
    if (wrappedSession != null) {
        session = VaadinSession.getForSession(request.getService(), wrappedSession);
    }

    SecurityContextHolder.clearContext();
    if (session != null) {
        logger.debug("Loading security context from VaadinSession {}", session);
        SecurityContext securityContext;
        session.lock();
        try {
            securityContext = (SecurityContext) session.getAttribute(SECURITY_CONTEXT_SESSION_ATTRIBUTE);
        } finally {
            session.unlock();
        }
        if (securityContext == null) {
            logger.debug("No security context found in VaadinSession {}", session);
        } else {
            logger.debug("Setting security context to {}", securityContext);
            SecurityContextHolder.setContext(securityContext);
        }
    } else {
        logger.debug("No VaadinSession available for retrieving the security context");
    }
}

From source file:nl.ctrlaltdev.harbinger.validator.TripwiredValidatorTest.java

@Test
public void shouldFullReportWithSpring() {
    SecurityContextHolder.setContext(new SecurityContextImpl());
    SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key", "user",
            Collections.singletonList(new SimpleGrantedAuthority("x"))));
    MockHttpServletRequest request = new MockHttpServletRequest();
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
    request.setRemoteAddr("192.168.1.1");
    request.addHeader("X-Forwarded-For", "8.8.8.8");
    request.setSession(new MockHttpSession());

    assertFalse(validator.isValid("../../etc/passwd", null));
}

From source file:hudson.plugins.gearman.SetDescriptionWorker.java

@Override
public GearmanJobResult executeFunction() {

    // check job results
    boolean jobResult = false;
    String jobResultMsg = "";

    String decodedData;//from  w w  w  .ja v  a 2s .  co  m
    // decode json
    try {
        decodedData = new String((byte[]) this.data, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("Unsupported encoding exception in argument");
    }

    // convert parameters passed in from client to hash map
    Gson gson = new Gson();
    Map<String, String> data = gson.fromJson(decodedData, new TypeToken<Map<String, String>>() {
    }.getType());

    // get build description
    String buildDescription = data.get("html_description");
    // get build id
    String jobName = data.get("name");
    String buildNumber = data.get("number");
    if (!jobName.isEmpty() && !buildNumber.isEmpty()) {
        // find build then update its description
        Run<?, ?> build = GearmanPluginUtil.findBuild(jobName, Integer.parseInt(buildNumber));
        if (build != null) {
            //SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM);
            SecurityContext oldContext = impersonate(ACL.SYSTEM);
            try {
                try {
                    build.setDescription(buildDescription);
                } catch (IOException e) {
                    throw new IllegalArgumentException(
                            "Unable to set description for " + jobName + ": " + buildNumber);
                }
            } finally {
                SecurityContextHolder.setContext(oldContext);
            }
            jobResultMsg = "Description for Jenkins build " + buildNumber + " was updated to "
                    + buildDescription;
            jobResult = true;
        } else {
            throw new IllegalArgumentException("Cannot find build number " + buildNumber);
        }
    } else {
        throw new IllegalArgumentException("Build id is invalid or not specified");
    }

    GearmanJobResult gjr = new GearmanJobResultImpl(this.jobHandle, jobResult, jobResultMsg.getBytes(), null,
            null, 0, 0);
    return gjr;
}

From source file:org.vaadin.spring.security.shared.PushSecurityInterceptor.java

@Override
public Action inspect(AtmosphereResource r) {
    final SecurityContextRepository securityContextRepo = getSecurityContextRepository(
            r.getAtmosphereConfig().getServletContext());
    if (securityContextRepo.containsContext(r.getRequest())) {
        LOGGER.trace("Loading the security context from the session");
        final HttpRequestResponseHolder requestResponse = new HttpRequestResponseHolder(r.getRequest(),
                r.getResponse());/*from   w ww.  j  ava  2 s.  c o  m*/
        final SecurityContext securityContext = securityContextRepo.loadContext(requestResponse);
        SecurityContextHolder.setContext(securityContext);
    }
    return Action.CONTINUE;
}

From source file:net.cristcost.study.services.ServiceTestUtil.java

private static void clearAuthentication(PrintWriter writer, SecurityContext oldContext) {
    if (oldContext != SecurityContextHolder.getContext()) {
        SecurityContextHolder.clearContext();
        SecurityContextHolder.setContext(oldContext);
        writer.println("@Restoring older context after secured session");
    }//from   ww w.  j a va  2  s.c  o m
}

From source file:test.pl.chilldev.facelets.taglib.spring.security.AuthenticationTagTest.java

@Test
public void applyNoAuthentication() throws FacesException {
    String property = "principal.username";
    String var = "bar";

    Map<String, Object> config = new HashMap<>();
    config.put(AuthenticationTag.ATTRIBUTE_PROPERTY, property);
    config.put(AuthenticationTag.ATTRIBUTE_VAR, var);

    AuthenticationTag tag = new AuthenticationTag(MockTagConfig.factory(config));

    // set up context
    FaceletContext context = new MockFaceletContext();
    SecurityContextHolder.setContext(this.securityContext);

    when(this.securityContext.getAuthentication()).thenReturn(null);

    // run the tag
    tag.apply(context, this.parent);

    assertNull("AuthenticationTag.apply() should set NULL value if there is no security context.",
            context.getAttribute(var));
}

From source file:org.terasoluna.gfw.security.web.logging.UserIdMDCPutFilterTest.java

@Test
public void testGetMDCValuePrincipalStringValue() {
    UserIdMDCPutFilter mdcPutFilter = new UserIdMDCPutFilter();

    // expected data
    String userName = "terasoluna@nttd.co.jp";

    securityContext = mock(SecurityContext.class);
    authentication = mock(Authentication.class);

    when(authentication.getPrincipal()).thenReturn(userName);
    when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);

    String mdcValueStr = mdcPutFilter.getMDCValue(request, response);
    // assert//from  w ww. jav  a2s.  c  o m
    assertThat(mdcValueStr, is(userName));
}

From source file:nl.ctrlaltdev.harbinger.validator.TripwiredValidatorTest.java

@Test
public void shouldFullReportWithSpringWithLogInjection() {
    SecurityContextHolder.setContext(new SecurityContextImpl());
    SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key", "user",
            Collections.singletonList(new SimpleGrantedAuthority("x"))));
    MockHttpServletRequest request = new MockHttpServletRequest();
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
    request.setRemoteAddr("192.168.1.1\n\r");
    request.addHeader("X-Forwarded-For", "\n\r\t8.8.8.8");
    request.setSession(new MockHttpSession());

    assertFalse(validator.isValid("../../etc/passwd\n\r\t", null));
}

From source file:hudson.plugins.gearman.SetDescriptionWorker.java

private SecurityContext impersonate(Authentication auth) {
    SecurityContext old = SecurityContextHolder.getContext();
    SecurityContextHolder.setContext(new NonSerializableSecurityContext(auth));
    return old;/*from  ww  w .j a  v  a  2  s.  c o m*/
}