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:cec.easyshop.storefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-email", method = RequestMethod.POST)
@RequireHardLogIn//from w  w  w.j a  v  a  2s  .  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.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// w  ww .  ja v a  2 s  .  co 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:com.skywell.social.custom.OAuth2AuthenticationProcessingFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {/*ww w.ja va  2 s .co  m*/

        Authentication authentication = tokenExtractor.extract(request);

        if (authentication == null) {
            if (stateless && isAuthenticated()) {
                if (debug) {
                    logger.debug("Clearing security context.");
                }
                SecurityContextHolder.clearContext();
            }
            if (debug) {
                logger.debug("No token in request, will continue chain.");
            }
        } else {
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
            if (authentication instanceof AbstractAuthenticationToken) {
                AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
                needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
            }
            User user = userRepository.findByAccessToken(authentication.getName());
            UsernamePasswordAuthenticationToken authenticate = new UsernamePasswordAuthenticationToken(
                    user.getProviderUserId(), user.getAccessToken(), user.getAuthorities());
            authenticate.setDetails(authentication.getDetails());

            SecurityContextHolder.getContext().setAuthentication(authenticate);

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

        if (debug) {
            logger.debug("Authentication request failed: " + failed);
        }
        eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed),
                new PreAuthenticatedAuthenticationToken("access-token", "N/A"));

        authenticationEntryPoint.commence(request, response,
                new InsufficientAuthenticationException(failed.getMessage(), failed));

        return;
    }

    chain.doFilter(request, response);
}

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  a2s . 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.apache.cxf.fediz.service.idp.service.security.GrantedAuthorityEntitlements.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    try {//from   w ww  .j a  va2s .c  o m
        Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
        if (currentAuth == null) {
            chain.doFilter(request, response);
            return;
        }

        final Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        if (currentAuth.getAuthorities() != null) {
            authorities.addAll(currentAuth.getAuthorities());
        }

        Iterator<? extends GrantedAuthority> authIt = currentAuth.getAuthorities().iterator();
        while (authIt.hasNext()) {
            GrantedAuthority ga = authIt.next();
            String roleName = ga.getAuthority();

            try {
                Role role = roleDAO.getRole(roleName.substring(5), Arrays.asList("all"));
                for (Entitlement e : role.getEntitlements()) {
                    authorities.add(new SimpleGrantedAuthority(e.getName()));
                }
            } catch (Exception ex) {
                LOG.error("Role '" + roleName + "' not found");
            }
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(authorities.toString());
        }
        UsernamePasswordAuthenticationToken enrichedAuthentication = new UsernamePasswordAuthenticationToken(
                currentAuth.getName(), currentAuth.getCredentials(), authorities);
        enrichedAuthentication.setDetails(currentAuth.getDetails());

        SecurityContextHolder.getContext().setAuthentication(enrichedAuthentication);
        LOG.info("Enriched AuthenticationToken added");

    } catch (Exception ex) {
        LOG.error("Failed to enrich security context with entitlements", ex);
    }

    chain.doFilter(request, response);
}

From source file:no.dusken.aranea.service.LoginDetailsServiceImpl.java

/**
 * Modify the current user's password. This should change the user's password in
 * the persistent user repository (datbase, LDAP etc) and should also modify the
 * current security context to contain the new password.
 *
 * @param oldPassword current password (for re-authentication if required)
 * @param newPassword the password to change to
 *///w w w  . j a v a  2  s  .  c  o m
public void changePassword(String oldPassword, String newPassword) {
    Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();

    if (currentUser == null) {
        // This would indicate bad coding somewhere
        throw new AccessDeniedException(
                "Can't change password as no Authentication object found in context " + "for current user.");
    }
    String username = currentUser.getName();
    LoginDetails user = (LoginDetails) loadUserByUsername(username);
    // If an authentication manager has been set, reauthenticate the user with the supplied password.
    if (authenticationManager != null) {
        logger.info("Reauthenticating user '{}' for password change request.", username);

        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, oldPassword));
    } else {
        logger.debug("No authentication manager set. Password won't be re-checked.");
    }
    logger.info("Changing password for user '{}'", username);
    String encoded = encoder.encodePassword(newPassword, username);
    user.setPassword(encoded);
    super.saveOrUpdate(user);
    //reauthenticating with the new password.
    UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(user,
            user.getPassword(), user.getAuthorities());
    newAuthentication.setDetails(currentUser.getDetails());
    SecurityContextHolder.getContext().setAuthentication(newAuthentication);
}

From source file:com.iisigroup.cap.base.aop.CapAuditLog4HandlerAdvice.java

private AuditLog loggedFunction(String TITLE, String targetName, Class clazz, Request params) {

    // ???( SysParm)
    String sysparmDisableData = sysProp.get(targetName + "." + DISABLE_TYPE);
    String dtype = CapString.trimNull(sysparmDisableData, DisableType.CANCEL.getCode());
    sysProp.put(targetName + "." + DISABLE_TYPE, dtype);
    if (DisableType.ALL.isEquals(dtype)) {
        logger.trace("{} {} DISABLE_AUDITLOG ALL!!", TITLE, targetName);
        return null;
    }/*from www . ja v a2 s  .c  o  m*/

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    Method method = CapBeanUtil.findMethod(clazz, params.get(CapConstants.P_FORM_ACTION), (Class<?>) null);
    String action = null, function = null;
    boolean haveToAudit = false;
    if (method != null) {
        CapAuditLogAction auditLogAction = method.getAnnotation(CapAuditLogAction.class);

        action = (auditLogAction != null && auditLogAction.actionType() != null)
                ? auditLogAction.actionType().toString()
                : null;
        function = (auditLogAction != null && auditLogAction.functionCode() != null)
                ? auditLogAction.functionCode().getCode()
                : null;
        if (action != null && function != null) {
            haveToAudit = true;
        }
    }

    String uid = null, ipAddress = null;

    CapUserDetails user = CapSecurityContext.getUser();
    if (user != null) {
        uid = user.getUserId();
        // ipAddress = user.getIpAddress();
    } else {
        uid = auth.getPrincipal().toString();
    }

    if (CapString.isEmpty(ipAddress) && auth != null && auth.getDetails() instanceof WebAuthenticationDetails) {
        WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
        ipAddress = details.getRemoteAddress();
    }
    if (CapString.isEmpty(ipAddress)) {
        ServletRequest req = params.getServletRequest();
        ipAddress = req.getRemoteAddr();
    }

    AuditLog auditLog = null;
    if (haveToAudit) {
        auditLog = new AuditLog();
        auditLog.setId(UUIDGenerator.getUUID());
        auditLog.setUserId(uid);
        auditLog.setIpAddress(trimByLen(CapString.trimNull(ipAddress), 50));
        auditLog.setFunctionId(trimByLen(function, 20));
        auditLog.setAction(trimByLen(action.toLowerCase(), 20));
        // auditLog.setRemark(trimByLen(CapString.trimNull(params.toString()),
        // 50));

        long tstart = NumberUtils.toLong(CapString.trimNull(params.get(CapConstants.C_AUDITLOG_START_TS)));
        if (tstart > 0) {
            auditLog.setExecuteDate(new Timestamp(tstart));
            if (logger.isTraceEnabled()) {
                logger.trace("{} AuditLog={}", TITLE, auditLog);
            }
        }
    }
    return auditLog;
}

From source file:org.syncope.core.security.SyncopeAuthenticationProvider.java

@Override
@Transactional(noRollbackFor = { BadCredentialsException.class })
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {

    boolean authenticated;
    SyncopeUser passwordUser = new SyncopeUser();
    SyncopeUser user = null;/*from w ww .  ja va2 s .  c  o m*/

    if (adminUser.equals(authentication.getPrincipal())) {
        passwordUser.setPassword(authentication.getCredentials().toString(), CipherAlgorithm.MD5, 0);

        authenticated = adminMD5Password.equalsIgnoreCase(passwordUser.getPassword());
    } else {
        String username;
        try {
            username = authentication.getPrincipal().toString();
        } catch (NumberFormatException e) {
            throw new UsernameNotFoundException("Invalid username: " + authentication.getName(), e);
        }

        user = userDAO.find(username);
        if (user == null) {
            throw new UsernameNotFoundException("Could not find user " + username);
        }

        passwordUser.setPassword(authentication.getCredentials().toString(), user.getCipherAlgoritm(), 0);

        authenticated = user.getPassword().equalsIgnoreCase(passwordUser.getPassword());
    }

    Authentication result;

    if ((user == null || !user.getSuspended()) && authenticated) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                authentication.getPrincipal(), null, userDetailsService
                        .loadUserByUsername(authentication.getPrincipal().toString()).getAuthorities());
        token.setDetails(authentication.getDetails());

        result = token;

        LOG.debug("User {} authenticated with roles {}", authentication.getPrincipal(), token.getAuthorities());

        if (user != null) {
            user.setLastLoginDate(new Date());
            user.setFailedLogins(0);
            userDAO.save(user);
        }

    } else {
        result = authentication;

        if (user != null && !user.getSuspended()) {
            user.setFailedLogins(user.getFailedLogins() + 1);
            userDAO.save(user);
        }

        LOG.debug("User {} not authenticated", authentication.getPrincipal());

        throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated");
    }

    return result;
}

From source file:org.axonframework.samples.trader.webui.security.TraderAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }//from  w w  w .  ja va 2 s .  c  o m
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName();
    String password = String.valueOf(token.getCredentials());
    FutureCallback<UserAccount> accountCallback = new FutureCallback<UserAccount>();
    AuthenticateUserCommand command = new AuthenticateUserCommand(username, password.toCharArray());
    try {
        commandBus.dispatch(new GenericCommandMessage<AuthenticateUserCommand>(command), accountCallback);
        // the bean validating interceptor is defined as a dispatch interceptor, meaning it is executed before
        // the command is dispatched.
    } catch (StructuralCommandValidationFailedException e) {
        return null;
    }
    UserAccount account;
    try {
        account = accountCallback.get();
        if (account == null) {
            throw new BadCredentialsException("Invalid username and/or password");
        }
    } catch (InterruptedException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    } catch (ExecutionException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(account,
            authentication.getCredentials(), userAuthorities);
    result.setDetails(authentication.getDetails());
    return result;
}