Example usage for org.springframework.security.core.context SecurityContext setAuthentication

List of usage examples for org.springframework.security.core.context SecurityContext setAuthentication

Introduction

In this page you can find the example usage for org.springframework.security.core.context SecurityContext setAuthentication.

Prototype

void setAuthentication(Authentication authentication);

Source Link

Document

Changes the currently authenticated principal, or removes the authentication information.

Usage

From source file:business.LargerExcerptListTests.java

@Test(groups = "request", dependsOnMethods = "approveRequest")
public void uploadExcerptList() throws IOException {
    UserAuthenticationToken palga = getPalga();
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(palga);

    RequestRepresentation representation = requestController.getRequestById(palga, processInstanceId);
    log.info("Status: " + representation.getStatus());

    log.info("Activity: " + representation.getActivityId());
    if (representation.getActivityId() == null) {
        for (Task task : taskService.createTaskQuery().list()) {
            log.info("Task " + task.getId() + ", process instance: " + task.getProcessInstanceId() + ", name: "
                    + task.getName() + ", key: " + task.getTaskDefinitionKey());
        }//ww w  . j  ava2  s  .co  m
    }

    log.info("uploadExcerptList: processInstanceId = " + processInstanceId);

    representation = requestController.claim(palga, processInstanceId, representation);

    ClassLoader classLoader = getClass().getClassLoader();
    URL resource = classLoader.getResource("test/Example excerptlist 20150521 v2.csv");
    InputStream input = resource.openStream();
    MultipartFile file = new MockMultipartFile(resource.getFile(), input);

    Integer flowTotalChunks = 1;
    Integer flowChunkNumber = 1;
    String flowIdentifier = "flow";

    int entryCount = requestController.uploadExcerptList(palga, processInstanceId, resource.getFile(),
            flowTotalChunks, flowChunkNumber, flowIdentifier, file);

    assertEquals(6, entryCount);

    SecurityContextHolder.clearContext();
}

From source file:business.LargerExcerptListTests.java

@Test(groups = "request", dependsOnMethods = "selectExcerpts")
public void approveSelection() {
    UserAuthenticationToken requester = getRequester();
    UserAuthenticationToken palga = getPalga();
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(requester);

    ((MockMailSender) mailSender).clear();

    RequestRepresentation representation = requestController.getRequestById(requester, processInstanceId);

    log.info("Status: " + representation.getStatus());

    securityContext.setAuthentication(palga);

    representation.setSelectionApproved(true);
    representation = selectionController.setExcerptSelectionApproval(palga, processInstanceId, representation);

    assertEquals(RequestStatus.LAB_REQUEST, representation.getStatus());

    assertEquals(2, labRequestService.count());
    List<LabRequest> labRequests = labRequestService.findAllByProcessInstanceId(processInstanceId);
    assertEquals(2, labRequests.size());

    int pathologyCount = 0;
    for (LabRequest labRequest : labRequests) {
        LabRequestRepresentation labRequestRepresentation = new LabRequestRepresentation(labRequest);
        labRequestService.transferLabRequestData(labRequestRepresentation, false);
        labRequestService.transferExcerptListData(labRequestRepresentation);
        labRequestService.transferLabRequestDetails(labRequestRepresentation, false);
        pathologyCount += labRequestRepresentation.getPathologyCount();
    }/*from w  ww.j ava  2 s.  com*/
    long pathologyCount2 = pathologyItemRepository.count();
    assertEquals(6, pathologyCount);
    assertEquals(6, pathologyCount2);

    // fails because contact data for labs is not set
    //assertEquals(2, ((MockMailSender)mailSender).getMessages().size());

    SecurityContextHolder.clearContext();
}

From source file:fr.treeptik.cloudunit.infinity.SimpleLongRunnerTestMR.java

@Before
public void setup() {
    logger.info("setup");

    this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();

    User user = null;//from  w  w w. j  a v a2s .co  m
    try {
        user = userService.findByLogin("johndoe");
    } catch (ServiceException e) {
        logger.error(e.getLocalizedMessage());
    }

    Authentication authentication = new UsernamePasswordAuthenticationToken(user.getLogin(),
            user.getPassword());
    Authentication result = authenticationManager.authenticate(authentication);
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(result);
    session = new MockHttpSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, 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//from   w w w  . j  a v  a 2 s .  c o m
        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:au.gov.dto.springframework.security.web.context.CookieSecurityContextRepository.java

/**
 * Obtains the security context for the supplied request. For an unauthenticated user, an empty context
 * implementation should be returned. This method should not return null.
 * <p>/*from ww  w. j  av a 2s .  c om*/
 * The use of the <tt>HttpRequestResponseHolder</tt> parameter allows implementations to return wrapped versions of
 * the request or response (or both), allowing them to access implementation-specific state for the request.
 * The values obtained from the holder will be passed on to the filter chain and also to the <tt>saveContext</tt>
 * method when it is finally called. Implementations may wish to return a subclass of
 * {@link SaveContextOnUpdateOrErrorResponseWrapper} as the response object, which guarantees that the context is
 * persisted when an error or redirect occurs.
 *
 * @param requestResponseHolder holder for the current request and response for which the context should be loaded.
 *
 * @return The security context which should be used for the current request, never null.
 */
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
    HttpServletRequest request = requestResponseHolder.getRequest();
    HttpServletResponse response = requestResponseHolder.getResponse();
    requestResponseHolder.setResponse(new SaveToCookieResponseWrapper(request, response));
    Cookie authenticationCookie = getAuthenticationCookie(request);
    if (authenticationCookie == null) {
        return SecurityContextHolder.createEmptyContext();
    }
    String serialisedAuthentication = tokenEncryption.decryptAndVerify(authenticationCookie.getValue());
    if (serialisedAuthentication == null) {
        response.addCookie(createExpireAuthenticationCookie(request));
        return SecurityContextHolder.createEmptyContext();
    }
    Authentication authentication = authenticationSerializer.deserialize(serialisedAuthentication);
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(authentication);
    return securityContext;
}

From source file:fi.helsinki.opintoni.SpringTest.java

protected void configureTeacherSecurityContext() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(new TestingAuthenticationToken(new AppUser.AppUserBuilder()
            .teacherNumber(TestConstants.TEACHER_NUMBER).eduPersonPrincipalName("opettaja@helsinki.fi")
            .eduPersonAffiliations(Arrays.asList(SAMLEduPersonAffiliation.FACULTY))
            .eduPersonPrimaryAffiliation(SAMLEduPersonAffiliation.FACULTY).teacherFacultyCode("A10000")
            .oodiPersonId("2222").build(), ""));
}

From source file:cn.org.once.cstack.users.UserControllerTestIT.java

@Before
public void setup() {
    logger.info("setup");

    this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();

    User user = null;/*from   w ww.j  ava 2 s.  c  o m*/
    try {
        user = userService.findByLogin("johndoe");
    } catch (ServiceException e) {
        logger.error(e.getLocalizedMessage());
    }

    Authentication authentication = null;
    if (user != null) {
        authentication = new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword());
    }
    Authentication result = authenticationManager.authenticate(authentication);
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(result);
    session = new MockHttpSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);
}

From source file:fi.helsinki.opintoni.SpringTest.java

protected void configureStudentSecurityContext() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(new TestingAuthenticationToken(
            new AppUser.AppUserBuilder().studentNumber(TestConstants.STUDENT_NUMBER)
                    .eduPersonPrincipalName("opiskelija@helsinki.fi")
                    .eduPersonAffiliations(
                            Arrays.asList(SAMLEduPersonAffiliation.MEMBER, SAMLEduPersonAffiliation.STUDENT))
                    .eduPersonPrimaryAffiliation(SAMLEduPersonAffiliation.STUDENT).oodiPersonId("1111").build(),
            ""));
}

From source file:cn.org.once.cstack.modules.ModulesControllerTestIT.java

@Before
public void setup() throws Exception {
    logger.info("setup");

    this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();

    User user = null;/*from  w ww  . j  a v a 2  s.c om*/
    try {
        user = userService.findByLogin("johndoe");
    } catch (ServiceException e) {
        logger.error(e.getLocalizedMessage());
    }

    assert user != null;
    Authentication authentication = new UsernamePasswordAuthenticationToken(user.getLogin(),
            user.getPassword());
    Authentication result = authenticationManager.authenticate(authentication);
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(result);
    session = new MockHttpSession();
    String secContextAttr = HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY;
    session.setAttribute(secContextAttr, securityContext);

}

From source file:cn.org.once.cstack.users.UserControllerTestIT.java

@Test
public void test10_userCreation() throws Exception {
    User user = null;/*from  w  w w.jav  a2 s  . c  o m*/
    try {
        user = userService.findByLogin("johndoe");
    } catch (ServiceException e) {
        logger.error(e.getLocalizedMessage());
    }

    Authentication authentication = null;
    if (user != null) {
        authentication = new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword());
    }
    Authentication result = authenticationManager.authenticate(authentication);
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(result);
    session = new MockHttpSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);

    final String login = "user10";
    final String password = "123456";
    final String email = "user10@gmail.com";
    final String firstName = "user";
    final String lastName = "user";
    final String organization = "treeptik";

    String jsonString = "{\"login\":\"" + login + "\", \"password\":\"" + password + "\", \"email\":\"" + email
            + "\", \"firstName\":\"" + firstName + "\", \"lastName\":\"" + lastName + "\", \"organization\":\""
            + organization + "\" }";
    mockMvc.perform(
            post("/user/signin").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString))
            .andDo(print()).andExpect(status().is2xxSuccessful());
}