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.mtt.myapp.AbstractSystemTransactionalTest.java

@Before
public void beforeSetSecurity() {
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("admin", null);
    SecurityContextImpl context = new SecurityContextImpl();
    context.setAuthentication(token);// www .ja  v  a2s. c o m
    SecurityContextHolder.setContext(context);
}

From source file:com.vdenotaris.spring.boot.security.saml.web.CommonTestSupport.java

public MockHttpSession mockHttpSession(boolean secured) {
    MockHttpSession mockSession = new MockHttpSession();
    SecurityContext mockSecurityContext = mock(SecurityContext.class);

    if (secured) {
        ExpiringUsernameAuthenticationToken principal = new ExpiringUsernameAuthenticationToken(null,
                USER_DETAILS, USER_NAME, AUTHORITIES);
        principal.setDetails(USER_DETAILS);
        when(mockSecurityContext.getAuthentication()).thenReturn(principal);
    }//from  w ww. jav  a  2 s .  c  o m

    SecurityContextHolder.setContext(mockSecurityContext);
    mockSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            mockSecurityContext);

    return mockSession;
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.LoginAuthenticationManagerTests.java

@Before
public void init() {
    manager.setApplicationEventPublisher(Mockito.mock(ApplicationEventPublisher.class));
    manager.setUserDatabase(userDatabase);
    oauth2Authentication = new OAuth2Authentication(
            new DefaultAuthorizationRequest("client", Arrays.asList("read", "write")), null);
    SecurityContextImpl context = new SecurityContextImpl();
    context.setAuthentication(oauth2Authentication);
    SecurityContextHolder.setContext(context);
}

From source file:org.ff4j.security.test.FlipSecurityTests.java

@After
public void tearDown() {
    SecurityContextHolder.setContext(securityCtx);
}

From source file:com.khs.sherpa.spring.SpringAuthentication.java

public String[] authenticate(String username, String password, HttpServletRequest request,
        HttpServletResponse response) {//  www.  j  ava2 s.com
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);

    Authentication authentication = null;

    try {
        authentication = authenticationManager.authenticate(token);
    } catch (AuthenticationException e) {
        throw new SherpaInvalidUsernamePassword("username and/or password is incorrect");
    }

    if (authentication.isAuthenticated() == false) {
        throw new SherpaInvalidUsernamePassword("username and/or password is incorrect");
    }

    List<String> roles = new ArrayList<String>();
    for (GrantedAuthority auth : authentication.getAuthorities()) {
        roles.add(auth.getAuthority());
    }

    SecurityContextImpl context = new SecurityContextImpl();
    context.setAuthentication(authentication);

    SecurityContextHolder.setContext(context);

    request.getSession().setAttribute("SPRING_SECURITY_CONTEXT_KEY", context);

    return roles.toArray(new String[roles.size()]);

}

From source file:org.openlmis.fulfillment.util.AuthenticationHelperTest.java

@Before
public void setUp() {
    when(authentication.getPrincipal()).thenReturn(userId);

    SecurityContext securityContext = mock(SecurityContext.class);
    when(securityContext.getAuthentication()).thenReturn(authentication);

    SecurityContextHolder.setContext(securityContext);
}

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

private static SecurityContext authenticate(PrintWriter writer, HttpServletRequest request,
        AuthenticationManager authenticationManager) {

    SecurityContext initialContext = SecurityContextHolder.getContext();

    if (request.getParameter("user") != null) {

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                request.getParameter("user"), request.getParameter("pass"));
        try {/*from   www.j a v a2s. c  om*/
            Authentication authentication = authenticationManager.authenticate(authRequest);
            SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            writer.println("Authenticating user: " + request.getParameter("user"));
        } catch (AuthenticationException e) {
            writer.println("! Error while Authenticating: " + e.getMessage());
        }
        writer.println();
    }

    return initialContext;
}

From source file:com.mastercard.test.spring.security.LogPrincipalRuleTests.java

@Test
public void ruleDoesNotBreakWhenAuthenticationIsNotProvided() throws Throwable {
    DefaultStatement statement = new DefaultStatement();
    Description description = Description.createTestDescription(MockWithMockUserTest.class.getName(), "test");

    LogPrincipalRule rule = new LogPrincipalRule();

    Statement actual = rule.apply(statement, description);

    SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());

    actual.evaluate();/*from   w  w w  .  j  av  a2 s  .co  m*/

    assertNotSame(statement, actual);
    assertTrue(statement.isEvaluated());
}

From source file:org.openmrs.contrib.metadatarepository.service.impl.UserSecurityAdviceTest.java

@Before
public void setUp() throws Exception {
    // store initial security context for later restoration
    initialSecurityContext = SecurityContextHolder.getContext();

    SecurityContext context = new SecurityContextImpl();
    User user = new User("user");
    user.setId(1L);//from   w  w w  .  j a v a  2s .c  o  m
    user.setPassword("password");
    user.addRole(new Role(Constants.USER_ROLE));

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(),
            user.getPassword(), user.getAuthorities());
    token.setDetails(user);
    context.setAuthentication(token);
    SecurityContextHolder.setContext(context);
}

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

@Override
protected void doCommonFilter(PortletRequest request, PortletResponse response, FilterChain chain)
        throws IOException, PortletException {
    if (request.getAttribute(FILTER_APPLIED) != null) {
        // ensure that filter is only applied once per request
        PortletFilterUtils.doFilter(request, response, chain);
        return;/*w  ww.  j a  va2s .c o m*/
    }

    final boolean debug = logger.isDebugEnabled();

    request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

    if (forceEagerSessionCreation) {
        PortletSession session = request.getPortletSession();

        if (debug && session.isNew()) {
            logger.debug("Eagerly created session: " + session.getId());
        }
    }

    PortletRequestResponseHolder holder = new PortletRequestResponseHolder(request, response);
    SecurityContext contextBeforeChainExecution = repo.loadContext(holder);

    try {
        SecurityContextHolder.setContext(contextBeforeChainExecution);

        PortletFilterUtils.doFilter(holder.getRequest(), holder.getResponse(), chain);

    } finally {
        SecurityContext contextAfterChainExecution = SecurityContextHolder.getContext();
        // Crucial removal of SecurityContextHolder contents - do this before anything else.
        SecurityContextHolder.clearContext();
        repo.saveContext(contextAfterChainExecution, holder);
        request.removeAttribute(FILTER_APPLIED);

        if (debug) {
            logger.debug("SecurityContextHolder now cleared, as request processing completed");
        }
    }
}