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.openmrs.contrib.metadatarepository.service.impl.UserSecurityAdviceTest.java

@Test
public void testAddUserAsAdmin() throws Exception {
    SecurityContext securityContext = new SecurityContextImpl();
    User user = new User("admin");
    user.setId(2L);/*from   www.jav a2  s. com*/
    user.setPassword("password");
    user.addRole(new Role(Constants.ADMIN_ROLE));
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(),
            user.getPassword(), user.getAuthorities());
    token.setDetails(user);
    securityContext.setAuthentication(token);
    SecurityContextHolder.setContext(securityContext);

    UserManager userManager = makeInterceptedTarget();
    final User adminUser = new User("admin");
    adminUser.setId(2L);

    context.checking(new Expectations() {
        {
            one(userDao).saveUser(with(same(adminUser)));
        }
    });

    userManager.saveUser(adminUser);
}

From source file:org.openinfinity.sso.security.spring.InjectableSecurityContextFilterBean.java

private void injectIdentityBasedSecurityContext(String sessionId) {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    SecurityContextHolder.setContext(securityContext);
    Authentication authentication = IdentityContext.loadIdentity(sessionId);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    LOGGER.info("SecurityContext created for active session based on IdentityContext for user: "
            + authentication.getName());
}

From source file:de.blizzy.documentr.web.FunctionsTest.java

@Before
public void setUp() {
    Functions.setGlobalRepositoryManager(repoManager);
    Functions.setPageStore(pageStore);/*from  w w w.j ava 2 s .c  om*/
    Functions.setUserStore(userStore);
    Functions.setPageRenderer(pageRenderer);
    Functions.setMarkdownProcessor(markdownProcessor);
    Functions.setMessageSource(messageSource);
    Functions.setMacroFactory(macroFactory);

    when(securityContext.getAuthentication()).thenReturn(authentication);

    SecurityContextHolder.setContext(securityContext);

    LocaleContextHolder.setLocale(LOCALE);

    ServletRequestAttributes requestAttrs = new ServletRequestAttributes(request);
    RequestContextHolder.setRequestAttributes(requestAttrs);
}

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

@Test
public void applyOutput() throws FacesException {

    String property = "principal.username";
    String username = "baz";

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

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

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

    when(this.securityContext.getAuthentication()).thenReturn(this.auth);
    when(this.auth.getPrincipal()).thenReturn(this.user);
    when(this.user.getUsername()).thenReturn(username);

    // run the tag
    UIOutput parent = new UIOutput();
    tag.apply(context, parent);//w w  w .  ja v  a  2 s  .  c  o m

    List<UIComponent> children = parent.getChildren();
    assertEquals("AuthenticationTag.apply() should add child component to current scope.", 1, children.size());

    UIComponent child = children.get(0);
    assertTrue("AuthenticationTag.apply() should add output component to current scope.",
            child instanceof UIOutput);

    assertEquals("AuthenticationTag.apply() should print authentication property.", username,
            ((UIOutput) child).getValue().toString());
}

From source file:se.vgregion.urlservice.controllers.BookmarkControllerTest.java

@After
public void after() {
    SecurityContextImpl ctx = new SecurityContextImpl();
    SecurityContextHolder.setContext(ctx);

}

From source file:org.apigw.authserver.web.controller.TokensControllerTest.java

private void mockSecurityContext() {
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    Mockito.when(authentication.getPrincipal()).thenReturn(new UserDetails() {
        @Override/*from   www .  j  av a  2  s  . co  m*/
        public boolean isEnabled() {
            return true;
        }

        @Override
        public boolean isCredentialsNonExpired() {
            return false;
        }

        @Override
        public boolean isAccountNonLocked() {
            return false;
        }

        @Override
        public boolean isAccountNonExpired() {
            return false;
        }

        @Override
        public String getUsername() {
            return CLIENT;
        }

        @Override
        public String getPassword() {
            return null;
        }

        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            authorities.add(new GrantedAuthorityImpl("A_ROLE"));
            return authorities;
        }
    });
    SecurityContextHolder.setContext(securityContext);
}

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

@Test
public void loadedContextContextIsCopiedToSecurityContextHolderAndUpdatedContextIsStored() throws Exception {
    final MockRenderRequest request = new MockRenderRequest();
    final MockRenderResponse response = new MockRenderResponse();
    final PortletSecurityContextRepository repo = mock(PortletSecurityContextRepository.class);
    PortletSecurityContextPersistenceFilter filter = new PortletSecurityContextPersistenceFilter(repo);
    final TestingAuthenticationToken beforeAuth = new TestingAuthenticationToken("someoneelse", "passwd",
            "ROLE_B");
    final SecurityContext scBefore = new SecurityContextImpl();
    final SecurityContext scExpectedAfter = new SecurityContextImpl();
    scExpectedAfter.setAuthentication(testToken);
    scBefore.setAuthentication(beforeAuth);
    when(repo.loadContext(any(PortletRequestResponseHolder.class))).thenReturn(scBefore);

    final FilterChain chain = mock(FilterChain.class);
    doAnswer(new Answer<Object>() {
        @Override/*ww  w  . j  ava  2 s  . com*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            assertEquals(beforeAuth, SecurityContextHolder.getContext().getAuthentication());
            // Change the context here
            SecurityContextHolder.setContext(scExpectedAfter);
            return null;
        }
    }).when(chain).doFilter(any(RenderRequest.class), any(RenderResponse.class));

    filter.doFilter(request, response, chain);

    verify(repo).saveContext(eq(scExpectedAfter), any(PortletRequestResponseHolder.class));
}

From source file:com.hp.autonomy.searchcomponents.hod.test.HodTestConfiguration.java

@PostConstruct
public void init() throws HodErrorException {
    final String apiKey = environment.getProperty(API_KEY_PROPERTY);
    final String application = environment.getProperty(APPLICATION_PROPERTY);
    final String domain = environment.getProperty(DOMAIN_PROPERTY);

    final AuthenticationService authenticationService = new AuthenticationServiceImpl(hodServiceConfig);
    final TokenProxy<EntityType.Application, TokenType.Simple> tokenProxy = authenticationService
            .authenticateApplication(new ApiKey(apiKey), application, domain, TokenType.Simple.INSTANCE);

    final HodAuthentication authentication = mock(HodAuthentication.class);
    final HodAuthenticationPrincipal hodAuthenticationPrincipal = mock(HodAuthenticationPrincipal.class);
    final ResourceIdentifier identifier = mock(ResourceIdentifier.class);
    when(identifier.toString()).thenReturn(application);
    when(identifier.getDomain()).thenReturn(domain);
    when(hodAuthenticationPrincipal.getApplication()).thenReturn(identifier);
    when(authentication.getPrincipal()).thenReturn(hodAuthenticationPrincipal);
    //noinspection unchecked,rawtypes
    when(authentication.getTokenProxy()).thenReturn((TokenProxy) tokenProxy);

    final SecurityContext securityContext = mock(SecurityContext.class);
    when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
}

From source file:org.openlmis.fulfillment.service.PermissionServiceTest.java

@Before
public void setUp() {
    SecurityContextHolder.setContext(securityContext);

    user.setId(order.getCreatedById());// w w  w. jav a2 s  .c om

    when(orderRepository.findOne(order.getId())).thenReturn(order);
    when(shipmentRepository.findOne(shipment.getId())).thenReturn(shipment);

    rightsMap.forEach((right, details) -> when(authenticationHelper.getRight(right)).thenReturn(details));

    when(authenticationHelper.getCurrentUser()).thenReturn(user);
    when(securityContext.getAuthentication()).thenReturn(userClient);

    ReflectionTestUtils.setField(permissionService, "serviceTokenClientId", SERVICE_CLIENT_ID);
    ReflectionTestUtils.setField(permissionService, "apiKeyPrefix", API_KEY_PREFIX);
}

From source file:org.apigw.authserver.web.controller.CertifiedClientsControllerTest.java

private void mockSecurityContext() {
    //SecurityContext access is done the static why hence we need
    //to mock it.
    authentication = Mockito.mock(Authentication.class);
    // Mockito.whens() for your authorization object
    securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    Mockito.when(securityContext.getAuthentication().getPrincipal()).thenReturn(new UserDetails() {
        @Override/* www  . ja v  a 2 s .  c o m*/
        public boolean isEnabled() {
            return true;
        }

        @Override
        public boolean isCredentialsNonExpired() {
            return false;
        }

        @Override
        public boolean isAccountNonLocked() {
            return false;
        }

        @Override
        public boolean isAccountNonExpired() {
            return false;
        }

        @Override
        public String getUsername() {
            return "USER";
        }

        @Override
        public String getPassword() {
            return "PASSWORD";
        }

        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            authorities.add(new GrantedAuthorityImpl("A_ROLE"));
            return authorities;
        }
    });

    //Set the Securitycontext for this test
    SecurityContextHolder.setContext(securityContext);
}