Example usage for org.springframework.security.core Authentication getDetails

List of usage examples for org.springframework.security.core Authentication getDetails

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getDetails.

Prototype

Object getDetails();

Source Link

Document

Stores additional details about the authentication request.

Usage

From source file:com.ushahidi.swiftriver.core.api.auth.crowdmapid.CrowdmapIDAuthenticationProvider.java

@Transactional(readOnly = true)
@Override//from  w w  w.j a  v  a2  s .  c om
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String username = authentication.getName();
    String password = authentication.getCredentials().toString();

    User user = userDao.findByUsernameOrEmail(username);

    if (user == null || !crowdmapIDClient.signIn(username, password)) {
        throw new BadCredentialsException(String.format("Invalid username/password pair for %s", username));
    }
    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
    for (Role role : user.getRoles()) {
        authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName().toUpperCase()));
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(username,
            authentication.getCredentials(), authorities);
    result.setDetails(authentication.getDetails());
    return result;
}

From source file:at.ac.univie.isc.asio.security.HttpMethodRestrictionFilter.java

@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final Authentication authentication = org.springframework.security.core.context.SecurityContextHolder
            .getContext().getAuthentication();
    if (authentication != null && HttpMethod.GET.name().equalsIgnoreCase(request.getMethod())) {
        logger.debug("applying " + RESTRICTION + " to " + authentication);
        Set<GrantedAuthority> restricted = RESTRICTION.mapAuthorities(authentication.getAuthorities());
        if (restricted.isEmpty()) { // anonymous and remember me tokens require at least one authority
            restricted = Collections.<GrantedAuthority>singleton(Role.NONE);
        }// w  ww . j  a v  a2s  .  c  o m
        if (!restricted.containsAll(authentication.getAuthorities())) {
            final AbstractAuthenticationToken replacement = copy(authentication, restricted);
            replacement.setDetails(authentication.getDetails());
            logger.debug("injecting " + replacement);
            org.springframework.security.core.context.SecurityContextHolder.getContext()
                    .setAuthentication(replacement);
        } else {
            logger.debug("skip restricting " + authentication + " as it contains no restricted authorities");
        }
    } else {
        logger.debug("skip restricting " + authentication + " on HTTP method " + request.getMethod());
    }
    chain.doFilter(request, response);
}

From source file:org.shaigor.rest.retro.client.oauth.OAuthPostAuthListener.java

@Override
public void onApplicationEvent(AbstractAuthenticationEvent event) {
    Authentication authentication = event.getAuthentication();

    if (event instanceof AuthenticationSuccessEvent) {
        ResourceOwnerPasswordResourceDetails resource = getResourceOwnerPasswordResourceDetails();
        resource.setScope(Arrays.asList("words"));
        resource.setUsername(authentication.getName());
        resource.setPassword(authentication.getCredentials().toString());

        try {/*from w  w  w .ja v a  2 s. co  m*/
            OAuth2AccessToken accessToken = accessTokenProvider.obtainAccessToken(resource,
                    new DefaultAccessTokenRequest());
            log.debug("Access token request succeeded for user: '{}', new token is '{}'",
                    resource.getUsername(), accessToken.getValue());
            if (authentication instanceof AbstractAuthenticationToken
                    && authentication.getDetails() instanceof CustomAuthenticationDetails) {
                ((CustomAuthenticationDetails) ((AbstractAuthenticationToken) authentication).getDetails())
                        .setBearer(accessToken.getValue());
                log.debug("Access token was added to authentication as details");
            } else if (log.isDebugEnabled()) {
                log.debug("Access token could not be added to authentication as details");
            }
        } catch (Exception e) {
            log.error("Access token request failed for user: '" + resource.getUsername() + "'", e);
        }
    }
    if (authentication instanceof CredentialsContainer) {
        // Authentication is complete. Remove credentials and other secret data from authentication
        ((CredentialsContainer) authentication).eraseCredentials();
    }

}

From source file:com.razorfish.security.AcceleratorAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : authentication.getName();//w ww. ja  v  a 2s  . co m
    String usernameResult = username;

    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

    if (!usernameResult.isEmpty()) {
        final List<CustomerModel> result = getCustomerDao().findCustomerByMobileNumber(usernameResult);
        if (!result.isEmpty()) {
            usernameResult = result.iterator().next().getOriginalUid();
            token = new UsernamePasswordAuthenticationToken(usernameResult,
                    (String) authentication.getCredentials());
            token.setDetails(authentication.getDetails());
        }
    }

    if (getBruteForceAttackCounter().isAttack(usernameResult)) {
        try {
            final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(usernameResult));
            userModel.setLoginDisabled(true);
            getModelService().save(userModel);
            bruteForceAttackCounter.resetUserCounter(userModel.getUid());
        } catch (final UnknownIdentifierException e) {
            LOG.warn("Brute force attack attempt for non existing user name " + usernameResult);
        } finally {
            throw new BadCredentialsException(
                    messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }

    checkCartForUser(usernameResult);
    return super.authenticate(token);
}

From source file:com.epam.cme.storefront.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 w  ww  .ja  v  a  2  s . c  o m*/

    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:com.acc.storefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-email", method = RequestMethod.POST)
@RequireHardLogIn/*from   ww  w .  ja va 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_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//from   w  ww .  j a  v  a2s  .  c om
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  w w . j  a v a2 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_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");
    }/*from   w w  w . j a  va  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;
}