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:sample.contact.ClientApplication.java

public void invokeContactService(Authentication authentication, int nrOfCalls) {
    StopWatch stopWatch = new StopWatch(nrOfCalls + " ContactService call(s)");
    Map<String, ContactService> contactServices = this.beanFactory.getBeansOfType(ContactService.class, true,
            true);//w w w.  j a  v a 2s  . co  m

    SecurityContextHolder.getContext().setAuthentication(authentication);

    for (String beanName : contactServices.keySet()) {
        Object object = this.beanFactory.getBean("&" + beanName);

        try {
            System.out.println("Trying to find setUsername(String) method on: " + object.getClass().getName());

            Method method = object.getClass().getMethod("setUsername", new Class[] { String.class });
            System.out.println("Found; Trying to setUsername(String) to " + authentication.getPrincipal());
            method.invoke(object, authentication.getPrincipal());
        } catch (NoSuchMethodException ignored) {
            System.out.println("This client proxy factory does not have a setUsername(String) method");
        } catch (IllegalAccessException ignored) {
            ignored.printStackTrace();
        } catch (InvocationTargetException ignored) {
            ignored.printStackTrace();
        }

        try {
            System.out.println("Trying to find setPassword(String) method on: " + object.getClass().getName());

            Method method = object.getClass().getMethod("setPassword", new Class[] { String.class });
            method.invoke(object, authentication.getCredentials());
            System.out.println("Found; Trying to setPassword(String) to " + authentication.getCredentials());
        } catch (NoSuchMethodException ignored) {
            System.out.println("This client proxy factory does not have a setPassword(String) method");
        } catch (IllegalAccessException ignored) {
        } catch (InvocationTargetException ignored) {
        }

        ContactService remoteContactService = contactServices.get(beanName);
        System.out.println("Calling ContactService '" + beanName + "'");

        stopWatch.start(beanName);

        List<Contact> contacts = null;

        for (int i = 0; i < nrOfCalls; i++) {
            contacts = remoteContactService.getAll();
        }

        stopWatch.stop();

        if (contacts.size() != 0) {
            for (Contact contact : contacts) {
                System.out.println("Contact: " + contact);
            }
        } else {
            System.out.println("No contacts found which this user has permission to");
        }

        System.out.println();
        System.out.println(stopWatch.prettyPrint());
    }

    SecurityContextHolder.clearContext();
}

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

@After
public void tearDown() {
    Functions.setGlobalRepositoryManager(null);
    Functions.setPageStore(null);//  w  w w .java 2 s.c o  m
    Functions.setUserStore(null);
    Functions.setPageRenderer(null);
    Functions.setMarkdownProcessor(null);
    Functions.setMessageSource(null);
    Functions.setMacroFactory(null);
    SecurityContextHolder.clearContext();
    LocaleContextHolder.resetLocaleContext();
    RequestContextHolder.resetRequestAttributes();
}

From source file:org.sharetask.controller.UserController.java

@RequestMapping(value = "/logout", method = RequestMethod.GET)
public void performLogout(final HttpServletRequest request, final HttpServletResponse response) {
    SecurityContextHolder.clearContext();
    final HttpSession session = request.getSession(false);
    if (session != null) {
        session.invalidate();/* ww  w  .j a va2s  . co  m*/
    }
}

From source file:es.mdef.clientmanager.ui.GestionClientesUI.java

CssLayout buildMenu() {
    // Add items/*  w ww .  j av a2 s .  c om*/
    menuItems.put("common", "Common UI Elements");
    menu.setSizeFull();
    menu.addComponent(getMenuTitleComponent());

    final MenuBar settings = new MenuBar();
    settings.addStyleName("user-menu");

    // TODO Actualizar nombre de usuario cuando se logee con exito
    final MenuBar.MenuItem userMenuItem = settings.addItem(getNombreUsuario(),
            new ThemeResource("icons/usuario.svg"), null);

    userMenuItem.addItem("Cambiar contrasea", new MenuBar.Command() {
        @Override
        public void menuSelected(MenuBar.MenuItem selectedItem) {
            ChangePasswordWindow changePasswordWindow = new ChangePasswordWindow();
            changePasswordWindow.center();
            addWindow(changePasswordWindow);
        }
    });
    userMenuItem.addSeparator();
    userMenuItem.addItem("Salir", new MenuBar.Command() {
        @Override
        public void menuSelected(MenuBar.MenuItem selectedItem) {
            SecurityContextHolder.clearContext();

            //UI.getCurrent().close();
            Navigator navigator = UI.getCurrent().getNavigator();
            navigator.navigateTo("");
        }
    });
    menu.addComponent(settings);

    menuItemsLayout.setPrimaryStyleName("valo-menuitems");
    menu.addComponent(menuItemsLayout);

    final Button clientesButton = new Button("Clientes", new Button.ClickListener() {
        @Override
        public void buttonClick(final Button.ClickEvent event) {
            navigator.navigateTo(CLIENT_LIST_VIEW);
        }
    });

    clientesButton.setHtmlContentAllowed(true);
    clientesButton.setPrimaryStyleName("valo-menu-item");
    clientesButton.setIcon(new ThemeResource("icons/clientes2.svg"));
    menuItemsLayout.addComponent(clientesButton);

    final Button budgetButton = new Button("Presupuesto", new Button.ClickListener() {
        @Override
        public void buttonClick(final Button.ClickEvent event) {
            navigator.navigateTo(BUDGETS_VIEW);
        }
    });

    budgetButton.setHtmlContentAllowed(true);
    budgetButton.setPrimaryStyleName("valo-menu-item");
    budgetButton.setIcon(new ThemeResource("icons/money.svg"));
    menuItemsLayout.addComponent(budgetButton);

    final Button subscripcionButton = new Button("Suscripciones", new Button.ClickListener() {
        @Override
        public void buttonClick(final Button.ClickEvent event) {
            navigator.navigateTo(PROVIDERS_VIEW);
        }
    });

    subscripcionButton.setHtmlContentAllowed(true);
    subscripcionButton.setPrimaryStyleName("valo-menu-item");
    subscripcionButton.setIcon(new ThemeResource("icons/suscripciones.svg"));
    menuItemsLayout.addComponent(subscripcionButton);

    return menu;
}

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

@POST
@Produces(MediaType.APPLICATION_JSON)/*from   w  ww  .j  a v a 2 s  .c  o  m*/
@Consumes(MediaType.APPLICATION_JSON)
@Path("changeEmail")
public UserDto changeEmail(ChangeEmailDto changeEmailDto, @Context HttpServletResponse response)
        throws BusinessException {
    User currentUser = currentUserService.getCurrentUser();
    User user = userServiceFacade.authenticateUser(currentUser.getEmail(), changeEmailDto.getPassword());
    user.setEmail(changeEmailDto.getEmail());
    userServiceFacade.saveUserPassword(user, changeEmailDto.getPassword());

    SecurityContextHolder.clearContext();

    UserDto userDto = new UserDto();
    userDto.setEmail(user.getEmail());
    userDto.setPassword(changeEmailDto.getPassword());
    return login(userDto, response);
}

From source file:hudson.model.DependencyGraphTest.java

/**
 * Tests that all dependencies are found even when some projects have restricted visibility.
 *//*from  w  w w.j a va2 s  .  c o m*/
@LocalData
@Bug(5265)
public void testItemReadPermission() throws Exception {
    // Rebuild dependency graph as anonymous user:
    hudson.rebuildDependencyGraph();
    try {
        // Switch to full access to check results:
        SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
        // @LocalData for this test has jobs w/o anonymous Item.READ
        AbstractProject up = (AbstractProject) hudson.getItem("hiddenUpstream");
        assertNotNull("hiddenUpstream project not found", up);
        List<AbstractProject> down = hudson.getDependencyGraph().getDownstream(up);
        assertEquals("Should have one downstream project", 1, down.size());
    } finally {
        SecurityContextHolder.clearContext();
    }
}

From source file:fr.esiea.windmeal.controller.authentication.AuthenticationCtrl.java

@RequestMapping(value = "/logout", method = RequestMethod.GET)
@ResponseBody/*from  w w  w . java 2  s.  c om*/
public void logout() throws InvalidLoginException, NeedToBeAuthenticatedException, DaoException {
    //Should may override spring security logout

    SecurityContext context = SecurityContextHolder.getContext();

    LOGGER.info("[Controller] Querying to log out User : \"" + context.getAuthentication().getName().toString()
            + "\"");

    if (context.getAuthentication() != null)
        SecurityContextHolder.clearContext();
}

From source file:cn.org.once.cstack.explorer.FileControllerTestIT.java

@After
public void teardown() throws Exception {
    SecurityContextHolder.clearContext();
    session.invalidate();
}

From source file:org.wicketopia.example.web.page.BasePage.java

@Override
protected void onInitialize() {
    super.onInitialize();
    setOutputMarkupId(true);//  w  w w  .java2 s. c  o m
    add(new Label("titleLabel", getTitleModel()).setRenderBodyOnly(true));
    add(new Label("captionLabel", getCaptionModel()).setRenderBodyOnly(true));
    add(new Label("copyrightLabel", resourceModel("page.copyright", new GregorianCalendar().get(Calendar.YEAR)))
            .setEscapeModelStrings(false));

    add(new FeedbackPanel("feedback").setOutputMarkupPlaceholderTag(true));
    add(new BookmarkablePageLink<Void>("homeLink", HomePage.class));
    add(new Link("login") {
        @Override
        public void onClick() {
            final UsernamePasswordAuthenticationToken tok = new UsernamePasswordAuthenticationToken("admin",
                    "admin");
            SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(tok));
            setResponsePage(BasePage.this.getClass());
        }

        @Override
        public boolean isVisible() {
            return SecurityContextHolder.getContext().getAuthentication() == null;
        }
    });
    add(new Link("logout") {
        @Override
        public void onClick() {
            SecurityContextHolder.clearContext();
            setResponsePage(BasePage.this.getClass());
        }

        @Override
        public boolean isVisible() {
            return SecurityContextHolder.getContext().getAuthentication() != null;
        }
    });
}

From source file:business.SelectionControllerTests.java

@Test(groups = "request", dependsOnMethods = "createRequest")
public void submitRequest() {
    UserAuthenticationToken requester = getRequester();
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(requester);

    RequestRepresentation representation = requestController.getRequestById(requester, processInstanceId);
    log.info("Status: " + representation.getStatus());
    representation.setTitle("Test request");
    representation.setPathologistEmail("test+pathologist@dntp.thehyve.nl");
    representation = requestController.submit(requester, processInstanceId, representation);
    log.info("Status: " + representation.getStatus());
    assertEquals(RequestStatus.REVIEW, representation.getStatus());

    SecurityContextHolder.clearContext();
}