Example usage for org.springframework.security.web.authentication.logout SecurityContextLogoutHandler SecurityContextLogoutHandler

List of usage examples for org.springframework.security.web.authentication.logout SecurityContextLogoutHandler SecurityContextLogoutHandler

Introduction

In this page you can find the example usage for org.springframework.security.web.authentication.logout SecurityContextLogoutHandler SecurityContextLogoutHandler.

Prototype

SecurityContextLogoutHandler

Source Link

Usage

From source file:com.itn.controller.IndexController.java

@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logoutPage(HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        new SecurityContextLogoutHandler().logout(request, response, auth);
    }/*from ww w  .j a  va 2  s  . c  om*/
    return "redirect:/login?logout";
}

From source file:com.coinblesk.server.controller.UserControllerAuthenticated.java

@RequestMapping(value = "/logout", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
public UserAccountStatusTO logout(HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    LOG.debug("Logout account for {}", auth.getName());
    if (auth != null) {
        new SecurityContextLogoutHandler().logout(request, response, auth);
    }//  w ww.  j a v  a  2s .c o m
    return new UserAccountStatusTO().setSuccess();
}

From source file:org.azrul.langkuik.Langkuik.java

public void initLangkuik(final EntityManagerFactory emf, final UI ui,
        final RelationManagerFactory relationManagerFactory, List<Class<?>> customTypeInterfaces) {

    List<Class<?>> rootClasses = new ArrayList<>();
    for (ManagedType<?> entity : emf.getMetamodel().getManagedTypes()) {
        Class<?> clazz = entity.getJavaType();
        if (clazz.getAnnotation(WebEntity.class).isRoot() == true) {
            rootClasses.add(clazz);/*from   ww w  .j ava2  s  . c  o  m*/
        }
    }

    //Manage custom type
    if (customTypeInterfaces == null) {
        customTypeInterfaces = new ArrayList<>();
    }
    //add system level custom type
    customTypeInterfaces.add(AttachmentCustomType.class);
    //create DAOs for custom types
    final List<DataAccessObject<?>> customTypeDaos = new ArrayList<>();
    for (Class<?> clazz : customTypeInterfaces) {
        customTypeDaos.add(new HibernateGenericDAO(emf, clazz));
    }

    //Setup page
    VerticalLayout main = new VerticalLayout();
    VerticalLayout content = new VerticalLayout();
    final Navigator navigator = new Navigator(ui, content);
    final HorizontalLayout breadcrumb = new HorizontalLayout();

    MenuBar menubar = new MenuBar();
    menubar.setId("MENUBAR");
    main.addComponent(menubar);
    main.addComponent(breadcrumb);
    main.addComponent(content);

    final Deque<History> history = new ArrayDeque<>();
    final Configuration config = Configuration.getInstance();

    history.push(new History("START", "Start"));
    StartView startView = new StartView(history, breadcrumb);
    navigator.addView("START", startView);
    MenuBar.MenuItem create = menubar.addItem("Create", null);
    MenuBar.MenuItem view = menubar.addItem("View", null);

    final PageParameter pageParameter = new PageParameter(customTypeDaos, emf, relationManagerFactory, history,
            config, breadcrumb);

    for (final Class rootClass : rootClasses) {
        final WebEntity myObject = (WebEntity) rootClass.getAnnotation(WebEntity.class);
        final DataAccessObject<?> dao = new HibernateGenericDAO<>(emf, rootClass);
        create.addItem("New " + myObject.name(), new MenuBar.Command() {
            @Override
            public void menuSelected(MenuBar.MenuItem selectedItem) {
                Object object = dao.createNew(true);
                BeanView<Object, ?> createNewView = new BeanView<>(object, null, null, pageParameter);
                String targetView = "CREATE_NEW_APPLICATION_" + UUID.randomUUID().toString();
                navigator.addView(targetView, (View) createNewView);
                history.clear();
                history.push(new History("START", "Start"));
                History his = new History(targetView, "Create new " + myObject.name());
                history.push(his);
                navigator.navigateTo(targetView);
            }
        });
        view.addItem("View " + myObject.name(), new MenuBar.Command() {
            @Override
            public void menuSelected(MenuBar.MenuItem selectedItem) {
                PlainTableView<?> seeApplicationView = new PlainTableView<>(rootClass, pageParameter);
                String targetView = "VIEW_APPLICATION_" + UUID.randomUUID().toString();
                navigator.addView(targetView, (View) seeApplicationView);
                history.clear();
                history.push(new History("START", "Start"));
                History his = new History(targetView, "View " + myObject.name());
                history.push(his);
                navigator.navigateTo(targetView);
            }
        });
    }

    menubar.addItem("Logout", null).addItem("Logout", new MenuBar.Command() {
        @Override
        public void menuSelected(MenuBar.MenuItem selectedItem) {
            ConfirmDialog.show(ui, "Please Confirm:", "Are you really sure you want to log out?", "I am",
                    "Not quite", new ConfirmDialog.Listener() {
                        @Override
                        public void onClose(ConfirmDialog dialog) {
                            if (dialog.isConfirmed()) {
                                HttpServletRequest req = (HttpServletRequest) VaadinService.getCurrentRequest();
                                HttpServletResponse resp = (HttpServletResponse) VaadinService
                                        .getCurrentResponse();
                                Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                                SecurityContextLogoutHandler ctxLogOut = new SecurityContextLogoutHandler();
                                ctxLogOut.logout(req, resp, auth);
                            }
                        }
                    });

        }
    });
    navigator.navigateTo("START");
    ui.setContent(main);
}

From source file:org.lightadmin.core.config.context.LightAdminSecurityConfiguration.java

@Bean
public Filter logoutFilter() {
    SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler();
    logoutHandler.setInvalidateHttpSession(false);
    LogoutFilter logoutFilter = new LogoutFilter(applicationUrl("/"), logoutHandler);
    logoutFilter.setFilterProcessesUrl(applicationUrl("/logout"));
    return logoutFilter;
}

From source file:de.thm.arsnova.config.SecurityConfig.java

@Bean
public SecurityContextLogoutHandler logoutHandler() {
    return new SecurityContextLogoutHandler();
}

From source file:eu.trentorise.smartcampus.permissionprovider.controller.AuthController.java

/**
 * Handles the redirection to the specified target after the login has been
 * performed. Given the user data collected during the login, updates the
 * user information in DB and populates the security context with the user
 * credentials.//  w w w.  ja va  2  s .  com
 * 
 * @param authorityUrl
 *            the authority used by the user to sign in.
 * @param target
 *            target functionality address.
 * @param req
 * @return
 * @throws Exception
 */
@RequestMapping("/eauth/{authorityUrl}")
public ModelAndView forward(@PathVariable String authorityUrl, @RequestParam(required = false) String target,
        HttpServletRequest req, HttpServletResponse res) throws Exception {
    List<GrantedAuthority> list = Collections
            .<GrantedAuthority>singletonList(new SimpleGrantedAuthority("ROLE_USER"));

    String nTarget = (String) req.getSession().getAttribute("redirect");
    if (nTarget == null)
        return new ModelAndView("redirect:/logout");

    String clientId = (String) req.getSession().getAttribute("client_id");
    if (clientId != null) {
        Set<String> idps = clientDetailsAdapter.getIdentityProviders(clientId);
        if (!idps.contains(authorityUrl)) {
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("message", "incorrect identity provider for the app");
            return new ModelAndView("oauth_error", model);
        }
    }

    // HOOK for testing
    if (testMode && target == null) {
        target = "/eauth/" + authorityUrl + "?target=" + URLEncoder.encode(nTarget, "UTF8")
                + "&OIDC_CLAIM_email=my@mail&OIDC_CLAIM_given_name=name&OIDC_CLAIM_family_name=surname";
    } else {

        if (!testMode && nTarget != null) {
            target = nTarget;
        }

        Authentication old = SecurityContextHolder.getContext().getAuthentication();
        if (old != null && old instanceof UsernamePasswordAuthenticationToken) {
            if (!authorityUrl.equals(old.getDetails())) {
                new SecurityContextLogoutHandler().logout(req, res, old);
                SecurityContextHolder.getContext().setAuthentication(null);

                req.getSession().setAttribute("redirect", target);
                req.getSession().setAttribute("client_id", clientId);

                return new ModelAndView("redirect:/eauth/" + authorityUrl);
                //               return new ModelAndView("redirect:/logout");
            }
        }

        List<NameValuePair> pairs = URLEncodedUtils.parse(URI.create(nTarget), "UTF-8");

        eu.trentorise.smartcampus.permissionprovider.model.User userEntity = null;
        if (old != null && old instanceof UsernamePasswordAuthenticationToken) {
            String userId = old.getName();
            userEntity = userRepository.findOne(Long.parseLong(userId));
        } else {
            userEntity = providerServiceAdapter.updateUser(authorityUrl, toMap(pairs), req);
        }

        UserDetails user = new User(userEntity.getId().toString(), "", list);

        AbstractAuthenticationToken a = new UsernamePasswordAuthenticationToken(user, null, list);
        a.setDetails(authorityUrl);

        SecurityContextHolder.getContext().setAuthentication(a);

    }
    return new ModelAndView("redirect:" + target);
}

From source file:at.fh.swenga.firefighters.controller.FireFighterController.java

@RequestMapping(value = "editFireBrigade", method = RequestMethod.POST)
public String editFireBrigade(@Valid @ModelAttribute FireBrigadeModel changedFireBrigade,
        BindingResult bindingResult, Model model, HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage += fieldError.getField() + " ist ungltig!";
        }/*from ww w  .  ja v  a  2 s . c  o  m*/
        model.addAttribute("errorMessage", errorMessage);
        return "forward:feuerwehr";
    }

    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        FireBrigadeModel fireBrigade = fireBrigadeRepository.findById(changedFireBrigade.getId());

        if (fireBrigade == null) {
            model.addAttribute("errorMessage", "Diese Feuerwehr kann nicht bearbeitet werden!");
        } else {
            fireBrigade.setName(changedFireBrigade.getName());
            fireBrigade.setPostalCode(changedFireBrigade.getPostalCode());
            fireBrigade.setPostTown(changedFireBrigade.getPostTown());
            fireBrigade.setStreetName(changedFireBrigade.getStreetName());
            fireBrigadeRepository.save(fireBrigade);
            model.addAttribute("message",
                    "Feuerwehr " + changedFireBrigade.getName() + " wurde erfolgreich gendert.");
        }
        return "forward:feuerwehr";

    } else {
        FireBrigadeModel fireBrigade = fireBrigadeRepository.findByIdAndName(changedFireBrigade.getId(),
                getSessionFireBrigade().getName());

        if (fireBrigade == null) {
            model.addAttribute("errorMessage", "Diese Feuerwehr kann nicht bearbeitet werden!");
            System.out.println("Falsche Feuerwehr!");
        } else {
            fireBrigade.setName(changedFireBrigade.getName());
            fireBrigade.setPostalCode(changedFireBrigade.getPostalCode());
            fireBrigade.setPostTown(changedFireBrigade.getPostTown());
            fireBrigade.setStreetName(changedFireBrigade.getStreetName());
            fireBrigadeRepository.save(fireBrigade);
            model.addAttribute("message",
                    "Feuerwehr " + changedFireBrigade.getName() + " wurde erfolgreich gendert!");
            new SecurityContextLogoutHandler().logout(request, null, null);
            return "redirect:login";
        }
        return "forward:feuerwehr";
    }
}

From source file:it.smartcommunitylab.aac.controller.AuthController.java

/**
 * Handles the redirection to the specified target after the login has been
 * performed. Given the user data collected during the login, updates the
 * user information in DB and populates the security context with the user
 * credentials./*from   w  w  w .j  a va  2s.co m*/
 * 
 * @param authorityUrl
 *            the authority used by the user to sign in.
 * @param target
 *            target functionality address.
 * @param req
 * @return
 * @throws Exception
 */
@RequestMapping("/eauth/{authorityUrl}")
public ModelAndView forward(@PathVariable String authorityUrl, @RequestParam(required = false) String target,
        HttpServletRequest req, HttpServletResponse res) {

    String nTarget = (String) req.getSession().getAttribute("redirect");
    if (nTarget == null)
        return new ModelAndView("redirect:/logout");

    String clientId = (String) req.getSession().getAttribute(OAuth2Utils.CLIENT_ID);
    if (clientId != null) {
        Set<String> idps = clientDetailsAdapter.getIdentityProviders(clientId);
        if (!idps.contains(authorityUrl)) {
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("message", "incorrect identity provider for the app");
            return new ModelAndView("oauth_error", model);
        }
    }

    AACOAuthRequest oauthRequest = (AACOAuthRequest) req.getSession()
            .getAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST);
    if (oauthRequest != null) {
        oauthRequest.setAuthority(authorityUrl);
        req.getSession().setAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST, oauthRequest);
    }

    target = nTarget;

    Authentication old = SecurityContextHolder.getContext().getAuthentication();
    if (old != null && old instanceof AACAuthenticationToken) {
        AACOAuthRequest oldDetails = (AACOAuthRequest) old.getDetails();
        if (oldDetails != null && !authorityUrl.equals(oldDetails.getAuthority())) {
            new SecurityContextLogoutHandler().logout(req, res, old);
            SecurityContextHolder.getContext().setAuthentication(null);

            req.getSession().setAttribute("redirect", target);
            req.getSession().setAttribute(OAuth2Utils.CLIENT_ID, clientId);

            return new ModelAndView("redirect:" + Utils.filterRedirectURL(authorityUrl));
        }
    }

    List<NameValuePair> pairs = URLEncodedUtils.parse(URI.create(nTarget), "UTF-8");

    it.smartcommunitylab.aac.model.User userEntity = null;
    if (old != null
            && (old instanceof AACAuthenticationToken || old instanceof RememberMeAuthenticationToken)) {
        String userId = old.getName();
        userEntity = userRepository.findOne(Long.parseLong(userId));
    } else {
        userEntity = providerServiceAdapter.updateUser(authorityUrl, toMap(pairs), req);
    }

    List<GrantedAuthority> list = roleManager.buildAuthorities(userEntity);

    UserDetails user = new User(userEntity.getId().toString(), "", list);
    AbstractAuthenticationToken a = new AACAuthenticationToken(user, null, authorityUrl, list);
    a.setDetails(oauthRequest);

    SecurityContextHolder.getContext().setAuthentication(a);

    if (rememberMeServices != null) {
        rememberMeServices.loginSuccess(req, res, a);
    }

    return new ModelAndView("redirect:" + target);
}

From source file:nu.localhost.tapestry5.springsecurity.services.SecurityModule.java

public static void contributeLogoutService(final OrderedConfiguration<LogoutHandler> cfg,
        @Inject RequestGlobals globals,//from w  w w .  j  av a 2s .  c o  m
        @InjectService("RememberMeLogoutHandler") final LogoutHandler rememberMeLogoutHandler) {

    cfg.add("securityContextLogoutHandler", new SecurityContextLogoutHandler());
    cfg.add("rememberMeLogoutHandler", rememberMeLogoutHandler);
    cfg.add("tapestryLogoutHandler", new TapestryLogoutHandler(globals), new String[0]);
}