Example usage for org.springframework.security.core.context SecurityContextHolder clearContext

List of usage examples for org.springframework.security.core.context SecurityContextHolder clearContext

Introduction

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

Prototype

public static void clearContext() 

Source Link

Document

Explicitly clears the context value from the current thread.

Usage

From source file:cn.org.once.cstack.security.SecurityTestIT.java

@After
public void teardown() {
    logger.info("*********************************");
    logger.info("             teardown            ");
    logger.info("*********************************");
    SecurityContextHolder.clearContext();
    session1.invalidate();/* w w w .ja v a 2  s .  c o  m*/
    session2.invalidate();
}

From source file:business.UploadTests.java

@Test(groups = "upload", dependsOnMethods = "createRequest")
public void uploadFileInvalidMimetype() throws IOException {
    UserAuthenticationToken requester = getRequester();
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(requester);

    RequestRepresentation representation = requestController.getRequestById(requester, processInstanceId);
    log.info("Status: " + representation.getStatus());
    int attachmentCount = representation.getAttachments().size();

    ClassLoader classLoader = getClass().getClassLoader();
    URL resource = classLoader.getResource("test/Utrecht_Oude_Gracht_Hamburgerbrug_(LOC).jpg");
    InputStream input = resource.openStream();
    MultipartFile file = new MockMultipartFile(resource.getFile(), resource.getFile().toString(), "undefined",
            input);//from w ww  .  j a v a  2  s.c  o  m

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

    representation = requestController.uploadRequestAttachment(requester, processInstanceId, resource.getFile(),
            flowTotalChunks, flowChunkNumber, flowIdentifier, file);

    assertEquals(attachmentCount + 1, representation.getAttachments().size());
    printFiles(representation.getAttachments());

    SecurityContextHolder.clearContext();
}

From source file:fr.mycellar.interfaces.web.services.security.SecurityWebService.java

@POST
@Path("logout")
public void logout(@Context HttpServletRequest httpServletRequest) {
    HttpSession session = httpServletRequest.getSession(false);
    if (session != null) {
        session.invalidate();/* w  w  w .  j  a  va  2  s.  co  m*/
    }

    SecurityContext context = SecurityContextHolder.getContext();
    context.setAuthentication(null);

    SecurityContextHolder.clearContext();
}

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:business.SelectionControllerTests.java

@Test(groups = "request", dependsOnMethods = "submitRequest")
public void submitRequestForApproval() {
    UserAuthenticationToken palga = getPalga();
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(palga);

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

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

    ((MockMailSender) mailSender).clear();

    // only enforced in front end, not in back end
    representation.setBackground("Background is testing.");
    representation.setHypothesis("Tests will pass");
    representation.setMethods("JUnit");
    // request type
    representation.setMaterialsRequest(true);
    representation.setPaReportRequest(true);
    // required checks
    representation.setRequesterValid(true);
    representation.setRequesterAllowed(true);
    representation.setContactPersonAllowed(true);
    representation.setRequesterLabValid(true);
    representation.setAgreementReached(true);

    representation = requestController.submitForApproval(palga, processInstanceId, representation);
    log.info("Status: " + representation.getStatus());
    assertEquals(RequestStatus.APPROVAL, representation.getStatus());

    assertEquals(mailSender.getClass(), MockMailSender.class);
    List<MimeMessage> emails = ((MockMailSender) mailSender).getMessages();
    assertEquals(1, emails.size());/*from w  w  w .  j  a  v  a  2 s .  c  o  m*/

    SecurityContextHolder.clearContext();
}

From source file:org.jasig.schedassist.web.register.RegistrationFlowHelper.java

/**
 * Invoke methods on the {@link OwnerDao} and {@link AvailableScheduleDao} to complete
 * the registration process.//www .  j a  v a  2 s  .com
 * 
 * @param registration
 * @throws IneligibleException
 * @throws ParseException 
 * @throws InputFormatException 
 */
public void executeRegistration(final Registration registration)
        throws IneligibleException, InputFormatException, ParseException {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    CalendarAccountUserDetailsImpl currentUser = (CalendarAccountUserDetailsImpl) authentication.getPrincipal();
    IScheduleOwner owner = ownerDao.register(currentUser.getCalendarAccount());
    owner = ownerDao.updatePreference(owner, Preferences.DURATIONS, registration.durationPreferenceValue());
    owner = ownerDao.updatePreference(owner, Preferences.LOCATION, registration.getLocation());
    owner = ownerDao.updatePreference(owner, Preferences.MEETING_PREFIX, registration.getTitlePrefix());
    owner = ownerDao.updatePreference(owner, Preferences.NOTEBOARD, registration.getNoteboard());
    owner = ownerDao.updatePreference(owner, Preferences.VISIBLE_WINDOW,
            registration.visibleWindowPreferenceKey());
    owner = ownerDao.updatePreference(owner, Preferences.DEFAULT_VISITOR_LIMIT,
            Integer.toString(registration.getDefaultVisitorsPerAppointment()));
    owner = ownerDao.updatePreference(owner, Preferences.MEETING_LIMIT,
            Integer.toString(registration.getMeetingLimitValue()));
    owner = ownerDao.updatePreference(owner, Preferences.REFLECT_SCHEDULE,
            Boolean.toString(registration.isReflectSchedule()));
    owner = ownerDao.updatePreference(owner, Preferences.REMINDERS, registration.emailReminderPreferenceKey());

    if (affiliationSource.doesAccountHaveAffiliation(owner.getCalendarAccount(), AffiliationImpl.ADVISOR)) {
        // set ADVISOR_SHARE_WITH_STUDENTS by default for all academic advisors
        owner = ownerDao.updatePreference(owner, Preferences.ADVISOR_SHARE_WITH_STUDENTS, "true");
    }
    if (affiliationSource.doesAccountHaveAffiliation(owner.getCalendarAccount(), AffiliationImpl.INSTRUCTOR)) {
        // set INSTRUCTOR_SHARE_WITH_STUDENTS by default for all instructors
        owner = ownerDao.updatePreference(owner, Preferences.INSTRUCTOR_SHARE_WITH_STUDENTS, "true");
    }
    if (registration.isScheduleSet()) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Set<AvailableBlock> blocks = AvailableBlockBuilder.createBlocks(registration.getStartTimePhrase(),
                registration.getEndTimePhrase(), registration.getDaysOfWeekPhrase(),
                dateFormat.parse(registration.getStartDatePhrase()),
                dateFormat.parse(registration.getEndDatePhrase()),
                registration.getDefaultVisitorsPerAppointment());
        availableScheduleDao.addToSchedule(owner, blocks);
    }

    if (registration.isReflectSchedule()) {
        reflectionService.reflectAvailableSchedule(owner);
    }

    // since Spring Security won't let you update someone's Authorities, have to force re-auth
    SecurityContextHolder.clearContext();
}

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

@After
public void teardown() throws Exception {
    logger.info("teardown");

    logger.info("Delete application : " + applicationName);

    mockMvc.perform(/*from w w w .j  a  v a  2  s  .co  m*/
            delete("/application/" + applicationName).session(session).contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());

    SecurityContextHolder.clearContext();
    session.invalidate();
}

From source file:org.appverse.web.framework.backend.security.authentication.userpassword.filters.CustomUserNamePasswordAuthenticationFilter.java

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final boolean debug = logger.isDebugEnabled();

    String uri = request.getRequestURI().substring(request.getContextPath().length());
    if (userNamePasswordAuthenticationUri == null || !uri.equals(userNamePasswordAuthenticationUri)) {
        chain.doFilter(request, response);
        return;//from w  w  w. ja v a2s  .c  o m
    }

    try {
        String[] tokens = extractUserNameAndPassword(request);
        assert tokens.length == 2;

        String username = tokens[0];

        if (debug) {
            logger.debug("Username and password attributes found for user '" + username + "'");
        }

        if (authenticationIsRequired(username)) {
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
                    tokens[1]);
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authResult = authenticationManager.authenticate(authRequest);

            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }

            SecurityContextHolder.getContext().setAuthentication(authResult);

            rememberMeServices.loginSuccess(request, response, authResult);

            onSuccessfulAuthentication(request, response, authResult);
        }

    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request for failed: " + failed);
        }

        rememberMeServices.loginFail(request, response);

        onUnsuccessfulAuthentication(request, response, failed);

        if (ignoreFailure) {
            chain.doFilter(request, response);
        } else {
            authenticationEntryPoint.commence(request, response, failed);
        }

        return;
    }

    chain.doFilter(request, response);
}

From source file:fr.treeptik.cloudunit.alias.AliasControllerTestIT.java

@After
public void teardown() {
    logger.info("**********************************");
    logger.info("           teardown               ");
    logger.info("**********************************");

    SecurityContextHolder.clearContext();
    session.invalidate();/*from   w  w w .  ja  v a2 s . c om*/
}