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:it.geosolutions.geoserver.sira.security.IrideSiraSecurityTest.java

private void login(String username, String password, String[] roles, IrideIdentity identity,
        Set<IrideInfoPersona> infoPersonae) {
    SecurityContextHolder.setContext(new SecurityContextImpl());

    final Set<GrantedAuthority> authorities = new LinkedHashSet<>();
    for (final String role : roles) {
        authorities.add(new GeoServerRole(role));
    }//from  w w  w  .j  a v a2 s . c  om

    final GeoServerUser user = new GeoServerUser(username);
    user.setAuthorities(authorities);
    user.setPassword(password);
    user.getProperties().put(IrideUserProperties.IRIDE_IDENTITY, identity);
    user.getProperties().put(IrideUserProperties.INFO_PERSONAE, infoPersonae);

    SecurityContextHolder.getContext()
            .setAuthentication(new UsernamePasswordAuthenticationToken(user, password, authorities));
}

From source file:de.blizzy.documentr.web.page.PageControllerTest.java

private void getPage(HttpServletRequest request) throws IOException {
    Date lastModified = new Date();
    when(pageStore.getPageMetadata(PROJECT, BRANCH, PAGE_PATH))
            .thenReturn(new PageMetadata("user", lastModified, 123, "commit")); //$NON-NLS-1$ //$NON-NLS-2$

    Page page = Page.fromText("title", "text"); //$NON-NLS-1$ //$NON-NLS-2$
    page.setViewRestrictionRole("viewRole"); //$NON-NLS-1$
    TestPageUtil.setParentPagePath(page, PARENT_PAGE);
    when(pageStore.getPage(PROJECT, BRANCH, PAGE_PATH, false)).thenReturn(page);

    SecurityContextHolder.setContext(createSecurityContext(anonymousAuthentication));
    String view = pageController.getPage(PROJECT, BRANCH, PAGE_PATH_URL, model, request, response);
    SecurityContextHolder.clearContext();
    assertEquals("/project/branch/page/view", view); //$NON-NLS-1$

    verify(model).addAttribute("path", PAGE_PATH); //$NON-NLS-1$
    verify(model).addAttribute("pageName", PAGE_NAME); //$NON-NLS-1$
    verify(model).addAttribute("parentPagePath", PARENT_PAGE); //$NON-NLS-1$
    verify(model).addAttribute("title", page.getTitle()); //$NON-NLS-1$
    verify(model).addAttribute("viewRestrictionRole", page.getViewRestrictionRole()); //$NON-NLS-1$
    verify(response).setDateHeader("Last-Modified", lastModified.getTime()); //$NON-NLS-1$
}

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

@Test
public void testAddUserRoleWhenHasAdminRole() throws Exception {
    SecurityContext securityContext = new SecurityContextImpl();
    User user1 = new User("user");
    user1.setId(1L);/*  w  ww. j a  v a  2  s .co  m*/
    user1.setPassword("password");
    user1.addRole(new Role(Constants.ADMIN_ROLE));
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user1.getUsername(),
            user1.getPassword(), user1.getAuthorities());
    token.setDetails(user1);
    securityContext.setAuthentication(token);
    SecurityContextHolder.setContext(securityContext);

    UserManager userManager = makeInterceptedTarget();
    final User user = new User("user");
    user.setId(1L);
    user.getRoles().add(new Role(Constants.ADMIN_ROLE));
    user.getRoles().add(new Role(Constants.USER_ROLE));

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

    userManager.saveUser(user);
}

From source file:architecture.ee.web.community.struts2.action.support.SocialCallbackSupport.java

private void createSecurityContext(User userToUse) {
    if (userToUse.getUserId() > 0) {
        ExtendedUserDetailsService detailsService = getComponent(ExtendedUserDetailsService.class);
        UserDetails details = detailsService.loadUserByUsername(userToUse.getUsername());
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(details,
                null, details.getAuthorities());
        SecurityContextImpl context = new SecurityContextImpl();
        context.setAuthentication(authentication);
        SecurityContextHolder.setContext(context);
        HttpSession httpsession = request.getSession(true);
        httpsession.setAttribute("SPRING_SECURITY_CONTEXT", context);
    }/*w  w  w  . j av  a2  s.  c o m*/
}

From source file:de.blizzy.documentr.web.page.PageControllerTest.java

@Test
public void getPageMustReturn404IfNotFound() throws IOException {
    when(request.getDateHeader(anyString())).thenReturn(-1L);

    when(pageStore.getPageMetadata(eq(PROJECT), eq(BRANCH), eq("nonexistent"))) //$NON-NLS-1$
            .thenThrow(new PageNotFoundException(PROJECT, BRANCH, "nonexistent")); //$NON-NLS-1$

    SecurityContextHolder.setContext(createSecurityContext(authenticatedAuthentication));
    String view = pageController.getPage(PROJECT, BRANCH, "nonexistent", model, request, response); //$NON-NLS-1$
    SecurityContextHolder.clearContext();
    assertEquals("/error/" + HttpServletResponse.SC_NOT_FOUND + "/page.notFound", removeViewPrefix(view)); //$NON-NLS-1$ //$NON-NLS-2$
    assertForward(view);/*from w  w w  .jav  a2 s  .  c om*/
}

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

@Test
public void noSessionIsCreatedIfSessionWasInvalidatedDuringTheRequest() throws Exception {
    PortletSessionSecurityContextRepository repo = new PortletSessionSecurityContextRepository();
    MockPortletRequest request = new MockPortletRequest();
    request.getPortletSession();//from  ww w . ja  va2 s .c  o  m
    MockPortletResponse response = new MockPortletResponse();
    PortletRequestResponseHolder holder = new PortletRequestResponseHolder(request, response);
    SecurityContextHolder.setContext(repo.loadContext(holder));
    SecurityContextHolder.getContext().setAuthentication(testToken);
    request.getPortletSession().invalidate();
    repo.saveContext(SecurityContextHolder.getContext(), holder);
    assertNull(request.getPortletSession(false));
}

From source file:net.shibboleth.idp.oidc.flow.PreAuthorizeUserApprovalAction.java

/**
 * Store spring security authentication context.
 *
 * @param profileRequestContext the profile request context
 * @param springRequestContext  the spring request context
 * @param authentication        the authentication
 *///from w  ww  .  jav a 2  s  .  co m
private void storeSpringSecurityAuthenticationContext(
        @Nonnull final ProfileRequestContext profileRequestContext, final RequestContext springRequestContext,
        final Authentication authentication) {
    final HttpServletRequest request = OIDCUtils.getHttpServletRequest(springRequestContext);
    if (request == null) {
        throw new OIDCException("HttpServletRequest cannot be null");
    }

    final SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(authentication);
    SecurityContextHolder.setContext(securityContext);
    final HttpSession session = request.getSession();
    session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
    log.debug("Stored authentication [{}] into Spring security context",
            SecurityContextHolder.getContext().getAuthentication());
}

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   ww  w  .  j  a  va 2s.  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 noSessionIsCreatedIfAnonymousTokenIsUsed() throws Exception {
    PortletSessionSecurityContextRepository repo = new PortletSessionSecurityContextRepository();
    MockPortletRequest request = new MockPortletRequest();
    MockPortletResponse response = new MockPortletResponse();
    PortletRequestResponseHolder holder = new PortletRequestResponseHolder(request, response);
    SecurityContextHolder.setContext(repo.loadContext(holder));
    SecurityContextHolder.getContext().setAuthentication(
            new AnonymousAuthenticationToken("key", "anon", AuthorityUtils.createAuthorityList("ANON")));
    repo.saveContext(SecurityContextHolder.getContext(), holder);
    assertNull(request.getPortletSession(false));
}

From source file:de.blizzy.documentr.web.page.PageControllerTest.java

@Test
public void getPageMustReturn304IfNotModified() throws IOException {
    when(session.getAttribute("authenticationCreationTime")).thenReturn( //$NON-NLS-1$
            new GregorianCalendar(2012, Calendar.JUNE, 2).getTime().getTime());

    when(request.getDateHeader("If-Modified-Since")).thenReturn( //$NON-NLS-1$
            new GregorianCalendar(2012, Calendar.JUNE, 9).getTimeInMillis());
    when(request.getSession()).thenReturn(session);

    when(pageStore.getPageMetadata(eq(PROJECT), eq(BRANCH), eq("nonexistent"))) //$NON-NLS-1$
            .thenReturn(new PageMetadata("user", new GregorianCalendar(2012, Calendar.JUNE, 1).getTime(), 123, //$NON-NLS-1$
                    "commit")); //$NON-NLS-1$

    TestPageUtil.clearProjectEditTimes();

    SecurityContextHolder.setContext(createSecurityContext(anonymousAuthentication));
    String view = pageController.getPage(PROJECT, BRANCH, "nonexistent", model, request, response); //$NON-NLS-1$
    SecurityContextHolder.clearContext();
    assertTrue(removeViewPrefix(view).startsWith("/error/" + HttpServletResponse.SC_NOT_MODIFIED + "/")); //$NON-NLS-1$ //$NON-NLS-2$
    assertForward(view);//  w w  w  .j av  a  2 s.  com
}