Example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken setDetails

List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken setDetails

Introduction

In this page you can find the example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken setDetails.

Prototype

public void setDetails(Object details) 

Source Link

Usage

From source file:com.acc.storefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-email", method = RequestMethod.POST)
@RequireHardLogIn//w  w  w  .ja v a  2 s.co m
public String updateEmail(final UpdateEmailForm updateEmailForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException {
    getEmailValidator().validate(updateEmailForm, bindingResult);

    String returnAction = REDIRECT_TO_PROFILE_PAGE;

    if (!bindingResult.hasErrors() && !updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
        bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {},
                "validation.checkEmail.equals");
    }

    if (bindingResult.hasErrors()) {
        returnAction = errorUpdatingEmail(model);
    } else {
        try {
            customerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword());
            GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER,
                    "text.account.profile.confirmationUpdated", null);

            // Replace the spring security authentication with the new UID
            final String newUid = customerFacade.getCurrentCustomer().getUid().toLowerCase();
            final Authentication oldAuthentication = SecurityContextHolder.getContext().getAuthentication();
            final UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
                    newUid, null, oldAuthentication.getAuthorities());
            newAuthentication.setDetails(oldAuthentication.getDetails());
            SecurityContextHolder.getContext().setAuthentication(newAuthentication);
        } catch (final DuplicateUidException e) {
            bindingResult.rejectValue("email", "profile.email.unique");
            returnAction = errorUpdatingEmail(model);
        } catch (final PasswordMismatchException passwordMismatchException) {
            bindingResult.rejectValue("password", "profile.currentPassword.invalid");
            returnAction = errorUpdatingEmail(model);
        }
    }

    return returnAction;
}

From source file:com.epam.storefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-email", method = RequestMethod.POST)
@RequireHardLogIn/*w  w w . java  2 s .  c o m*/
public String updateEmail(final UpdateEmailForm updateEmailForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectAttributes, final HttpServletRequest request)
        throws CMSItemNotFoundException {
    getEmailValidator().validate(updateEmailForm, bindingResult);

    String returnAction = REDIRECT_TO_PROFILE_PAGE;

    if (!bindingResult.hasErrors() && !updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
        bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {},
                "validation.checkEmail.equals");
    }

    if (bindingResult.hasErrors()) {
        returnAction = errorUpdatingEmail(model);
    } else {
        try {
            customerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword());
            GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER,
                    "text.account.profile.confirmationUpdated", null);

            // Replace the spring security authentication with the new UID
            final String newUid = customerFacade.getCurrentCustomer().getUid().toLowerCase();
            final Authentication oldAuthentication = SecurityContextHolder.getContext().getAuthentication();
            final UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
                    newUid, null, oldAuthentication.getAuthorities());
            newAuthentication.setDetails(oldAuthentication.getDetails());
            SecurityContextHolder.getContext().setAuthentication(newAuthentication);
        } catch (final DuplicateUidException e) {
            bindingResult.rejectValue("email", "profile.email.unique");
            returnAction = errorUpdatingEmail(model);
        } catch (final PasswordMismatchException passwordMismatchException) {
            bindingResult.rejectValue("password", "profile.currentPassword.invalid");
            returnAction = errorUpdatingEmail(model);
        }
    }

    return returnAction;
}

From source file:com.ctc.storefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-email", method = RequestMethod.POST)
@RequireHardLogIn/*from w ww.j a v  a 2s .c  o  m*/
public String updateEmail(final UpdateEmailForm updateEmailForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException {
    getEmailValidator().validate(updateEmailForm, bindingResult);
    String returnAction = REDIRECT_TO_UPDATE_EMAIL_PAGE;

    if (!bindingResult.hasErrors() && !updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
        bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {},
                "validation.checkEmail.equals");
    }

    if (bindingResult.hasErrors()) {
        returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE);
    } else {
        try {
            customerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword());
            GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER,
                    "text.account.profile.confirmationUpdated", null);

            // Replace the spring security authentication with the new UID
            final String newUid = customerFacade.getCurrentCustomer().getUid().toLowerCase();
            final Authentication oldAuthentication = SecurityContextHolder.getContext().getAuthentication();
            final UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
                    newUid, null, oldAuthentication.getAuthorities());
            newAuthentication.setDetails(oldAuthentication.getDetails());
            SecurityContextHolder.getContext().setAuthentication(newAuthentication);
        } catch (final DuplicateUidException e) {
            bindingResult.rejectValue("email", "profile.email.unique");
            returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE);
        } catch (final PasswordMismatchException passwordMismatchException) {
            bindingResult.rejectValue("password", PROFILE_CURRENT_PASSWORD_INVALID);
            returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE);
        }
    }

    return returnAction;
}

From source file:com.epam.trade.storefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-email", method = RequestMethod.POST)
public String updateEmail(final UpdateEmailForm updateEmailForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectAttributes, final HttpServletRequest request)
        throws CMSItemNotFoundException {
    getEmailValidator().validate(updateEmailForm, bindingResult);

    String returnAction = REDIRECT_TO_PROFILE_PAGE;

    if (!bindingResult.hasErrors() && !updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
        bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {},
                "validation.checkEmail.equals");
    }/*ww w  .  j a v a  2  s .  co m*/

    if (bindingResult.hasErrors()) {
        returnAction = errorUpdatingEmail(model);
    } else {
        try {
            customerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword());
            GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER,
                    "text.account.profile.confirmationUpdated", null);

            // Replace the spring security authentication with the new UID
            final String newUid = customerFacade.getCurrentCustomer().getUid().toLowerCase();
            final Authentication oldAuthentication = SecurityContextHolder.getContext().getAuthentication();
            final UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
                    newUid, null, oldAuthentication.getAuthorities());
            newAuthentication.setDetails(oldAuthentication.getDetails());
            SecurityContextHolder.getContext().setAuthentication(newAuthentication);
        } catch (final DuplicateUidException e) {
            bindingResult.rejectValue("email", "profile.email.unique");
            returnAction = errorUpdatingEmail(model);
        } catch (final PasswordMismatchException passwordMismatchException) {
            bindingResult.rejectValue("password", "profile.currentPassword.invalid");
            returnAction = errorUpdatingEmail(model);
        }
    }

    return returnAction;
}

From source file:cec.easyshop.storefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-email", method = RequestMethod.POST)
@RequireHardLogIn//from  ww w  . j a  va2s. c  om
public String updateEmail(final UpdateEmailForm updateEmailForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException {
    getEmailValidator().validate(updateEmailForm, bindingResult);
    String returnAction = REDIRECT_TO_UPDATE_EMAIL_PAGE;

    if (!bindingResult.hasErrors() && !updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
        bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {},
                "validation.checkEmail.equals");
    }

    if (bindingResult.hasErrors()) {
        returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE);
    } else {
        try {
            customerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword());
            GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER,
                    "text.account.profile.confirmationUpdated", null);

            // Replace the spring security authentication with the new UID
            final String newUid = customerFacade.getCurrentCustomer().getUid().toLowerCase();
            final Authentication oldAuthentication = SecurityContextHolder.getContext().getAuthentication();
            final UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
                    newUid, null, oldAuthentication.getAuthorities());
            newAuthentication.setDetails(oldAuthentication.getDetails());
            SecurityContextHolder.getContext().setAuthentication(newAuthentication);
        } catch (final DuplicateUidException e) {
            bindingResult.rejectValue("email", "profile.email.unique");
            returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE);
        } catch (final PasswordMismatchException passwordMismatchException) {
            bindingResult.rejectValue("password", "profile.currentPassword.invalid");
            returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE);
        }
    }

    return returnAction;
}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-email", method = RequestMethod.POST)
@RequireHardLogIn// www. j  a  v a2 s.c  o m
public String updateEmail(@Valid final UpdateEmailForm updateEmailForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException {
    String returnAction = REDIRECT_TO_PROFILE_PAGE;

    if (!updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
        bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {},
                "validation.checkEmail.equals");
    }

    if (bindingResult.hasErrors()) {
        returnAction = errorUpdatingEmail(model);
    } else {
        try {
            customerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword());
            GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER,
                    "text.account.profile.confirmationUpdated");

            // Replace the spring security authentication with the new UID
            final String newUid = customerFacade.getCurrentCustomer().getUid().toLowerCase();
            final Authentication oldAuthentication = SecurityContextHolder.getContext().getAuthentication();
            final UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
                    newUid, null, oldAuthentication.getAuthorities());
            newAuthentication.setDetails(oldAuthentication.getDetails());
            SecurityContextHolder.getContext().setAuthentication(newAuthentication);
        } catch (final DuplicateUidException e) {
            bindingResult.rejectValue("email", "profile.email.unique");
            returnAction = errorUpdatingEmail(model);
        } catch (final PasswordMismatchException passwordMismatchException) {
            bindingResult.rejectValue("email", "profile.currentPassword.invalid");
            returnAction = errorUpdatingEmail(model);
        }
    }

    return returnAction;
}

From source file:de.hybris.platform.ytelcoacceleratorstorefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-email", method = RequestMethod.POST)
public String updateEmail(@Valid final UpdateEmailForm updateEmailForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException {
    String returnAction = REDIRECT_TO_PROFILE_PAGE;

    if (!updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
        bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {},
                "validation.checkEmail.equals");
    }//from  ww  w.  j a  v a 2 s.  c  om

    if (bindingResult.hasErrors()) {
        GlobalMessages.addErrorMessage(model, "form.global.error");
        storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
        setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
        model.addAttribute("breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile"));
        returnAction = ControllerConstants.Views.Pages.Account.AccountProfileEmailEditPage;
    } else {
        try {
            customerFacade.changeUid(updateEmailForm.getEmail().toLowerCase(), updateEmailForm.getPassword());

            //temporary solution to set oryginal UID - with new version of commerceservices it will not be necessary
            final CustomerData customerData = customerFacade.getCurrentCustomer();
            customerData.setDisplayUid(updateEmailForm.getEmail());
            customerFacade.updateProfile(customerData);
            //end of temporary solution

            redirectAttributes.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER,
                    Collections.singletonList("text.account.profile.confirmationUpdated"));

            // Replace the spring security authentication with the new UID
            final String newUid = customerFacade.getCurrentCustomer().getUid().toLowerCase();
            final Authentication oldAuthentication = SecurityContextHolder.getContext().getAuthentication();
            final UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
                    newUid, null, oldAuthentication.getAuthorities());
            newAuthentication.setDetails(oldAuthentication.getDetails());
            SecurityContextHolder.getContext().setAuthentication(newAuthentication);
        } catch (final DuplicateUidException e) {
            redirectAttributes.addFlashAttribute(GlobalMessages.INFO_MESSAGES_HOLDER,
                    Collections.singletonList("text.account.profile.emailNotChanged"));
        } catch (final PasswordMismatchException passwordMismatchException) {
            bindingResult.rejectValue("email", "profile.currentPassword.invalid");
            GlobalMessages.addErrorMessage(model, "form.global.error");
            storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
            setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
            model.addAttribute("breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile"));
            returnAction = ControllerConstants.Views.Pages.Account.AccountProfileEmailEditPage;
        }
    }

    return returnAction;
}

From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenDeserializer.java

/**
 * This method construct {@link UsernamePasswordAuthenticationToken} object from serialized json.
 *//*from w  ww.j av  a 2  s.  c o  m*/
@Override
public UsernamePasswordAuthenticationToken deserialize(JsonParser jsonParser, DeserializationContext context)
        throws IOException, JsonProcessingException {
    UsernamePasswordAuthenticationToken token;
    ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
    JsonNode jsonNode = mapper.readTree(jsonParser);
    Boolean authenticated = readJsonNode(jsonNode, "authenticated").asBoolean();
    JsonNode principalNode = readJsonNode(jsonNode, "principal");
    Object principal;
    if (principalNode.isObject()) {
        Class principalClass = LinkedHashMap.class;
        if (principalNode.hasNonNull("@class")) {
            try {
                principalClass = Class.forName(principalNode.get("@class").asText());
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(
                        "Could not load principal class [" + principalNode.get("@class").asText() + "]", e);
            }
        }
        principal = mapper.readValue(principalNode.toString(), principalClass);
    } else {
        principal = principalNode.asText();
    }
    Object credentials = readJsonNode(jsonNode, "credentials").asText();
    List<GrantedAuthority> authorities = mapper.readValue(readJsonNode(jsonNode, "authorities").toString(),
            new TypeReference<List<GrantedAuthority>>() {
            });
    if (authenticated) {
        token = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
    } else {
        token = new UsernamePasswordAuthenticationToken(principal, credentials);
    }
    token.setDetails(readJsonNode(jsonNode, "details"));
    return token;
}

From source file:com.esquema.seguridad.AutenticacionPersonalizada.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    UsernamePasswordAuthenticationToken auth;
    String usuario = String.valueOf(authentication.getPrincipal());
    //System.out.println("Usuario..: " + usuario);

    String password = null;// w  ww  . j  av  a2 s  .  c  om
    try {
        //password = encr.encr(authentication.getCredentials().toString());
        password = authentication.getCredentials().toString();
        //System.out.println("Passwordss..: " + password);

    } catch (Exception ex) {
        Logger.getLogger(AutenticacionPersonalizada.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (usuario.isEmpty() && !password.isEmpty()) {
        throw new BadCredentialsException("Usuario no vlido");
    }

    if (password.isEmpty() && !usuario.isEmpty()) {
        throw new BadCredentialsException("Clave no vlida");
    }

    if (usuario.isEmpty() && password.isEmpty()) {
        throw new BadCredentialsException("Credenciales no vlidas");
    }

    //Llamado al mtodo encuentra. Est ms arriba.
    s_user usuarioBD = encuentra(usuario);

    if (usuarioBD.getEnabled() == 0) {
        throw new BadCredentialsException("El usuario [" + usuario.toUpperCase() + "] se encuentra bloqueado");
    }

    /*
    System.out.println("Clave de HTTPS..: " + clave);
    System.out.println("Resultado del query..: " + usuarioBD);
    System.out.println("Usuario BD..: " + usuarioBD.getUserlogin());
    System.out.println("Password BD..: " + usuarioBD.getPasswd());
    */

    if (usuarioBD.getIs_ldap() == 1) {
        try {
            ldapTemplate.afterPropertiesSet();
        } catch (Exception ex) {
            Logger.getLogger(AutenticacionPersonalizada.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Perform the authentication.
        Filter filter = new EqualsFilter("sAMAccountName", usuario);

        if (!ldapTemplate.authenticate(env.getProperty("ldap.base"), filter.encode(), password)) {
            throw new BadCredentialsException("Clave o Usuario invlido");
        }
    } else {

        String clave = null;
        try {
            //create MD5 hash using the string: userlogin:passwd
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] b = (usuario + ":" + password).getBytes();
            //byte[] b = (password).getBytes();
            byte[] hash = md.digest(b);
            clave = Base64.encodeToString(hash, true);
        } catch (Exception ex) {
            Logger.getLogger(AutenticacionPersonalizada.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (usuarioBD == null || (!clave.equals(usuarioBD.getPasswd()))) {
            throw new BadCredentialsException("Clave o Usuario invlido");
        }
    }

    /*
    System.out.println("Usuario BD..: " + usuarioBD.getUserlogin());
    System.out.println("Password BD..: " + usuarioBD.getPasswd());
    */
    List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
    grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));

    auth = new UsernamePasswordAuthenticationToken(usuario, password, grantedAuths);
    auth.setDetails(usuarioBD);

    return auth;
}