Example usage for org.springframework.web.context.request RequestContextHolder currentRequestAttributes

List of usage examples for org.springframework.web.context.request RequestContextHolder currentRequestAttributes

Introduction

In this page you can find the example usage for org.springframework.web.context.request RequestContextHolder currentRequestAttributes.

Prototype

public static RequestAttributes currentRequestAttributes() throws IllegalStateException 

Source Link

Document

Return the RequestAttributes currently bound to the thread.

Usage

From source file:com.cws.us.pws.controllers.CommonController.java

@RequestMapping(value = "/contact", method = RequestMethod.POST)
public final ModelAndView sendMessage(@ModelAttribute("message") final EmailMessage message,
        final BindingResult bindResult) {
    final String methodName = CommonController.CNAME
            + "#sendMessage(@ModelAttribute(\"message\") final EmailMessage message, final BindingResult bindResult)";

    if (DEBUG) {//ww  w  .  ja va  2 s  . c om
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("EmailMessage: {}", message);
        DEBUGGER.debug("BindingResult: {}", bindResult);
    }

    ModelAndView mView = new ModelAndView();

    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpServletRequest hRequest = requestAttributes.getRequest();
    final HttpSession hSession = hRequest.getSession();

    if (DEBUG) {
        DEBUGGER.debug("ServletRequestAttributes: {}", requestAttributes);
        DEBUGGER.debug("HttpServletRequest: {}", hRequest);
        DEBUGGER.debug("HttpSession: {}", hSession);
        DEBUGGER.debug("Session ID: {}", hSession.getId());

        DEBUGGER.debug("Dumping session content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> sessionEnumeration = hSession.getAttributeNames();

        while (sessionEnumeration.hasMoreElements()) {
            String sessionElement = sessionEnumeration.nextElement();
            Object sessionValue = hSession.getAttribute(sessionElement);

            DEBUGGER.debug("Attribute: " + sessionElement + "; Value: " + sessionValue);
        }

        DEBUGGER.debug("Dumping request content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> requestEnumeration = hRequest.getAttributeNames();

        while (requestEnumeration.hasMoreElements()) {
            String requestElement = requestEnumeration.nextElement();
            Object requestValue = hRequest.getAttribute(requestElement);

            DEBUGGER.debug("Attribute: " + requestElement + "; Value: " + requestValue);
        }

        DEBUGGER.debug("Dumping request parameters:");
        @SuppressWarnings("unchecked")
        Enumeration<String> paramsEnumeration = hRequest.getParameterNames();

        while (paramsEnumeration.hasMoreElements()) {
            String requestElement = paramsEnumeration.nextElement();
            Object requestValue = hRequest.getParameter(requestElement);

            DEBUGGER.debug("Parameter: " + requestElement + "; Value: " + requestValue);
        }
    }

    // validate
    this.appConfig.getEmailValidator().validate(message, bindResult);

    if (bindResult.hasErrors()) {
        // errors occurred during validation
        ERROR_RECORDER.error("Form failed field validation");

        mView.addObject(Constants.ERROR_MESSAGE, this.appConfig.getMessageValidationFailed());
        mView.addObject("command", new EmailMessage());
        mView.setViewName(this.appConfig.getContactPage());

        if (DEBUG) {
            DEBUGGER.debug("ModelAndView: {}", mView);
        }

        return mView;
    }

    this.appConfig.getMessageValidator().validate(message, bindResult);

    if (bindResult.hasErrors()) {
        // errors occurred during validation
        ERROR_RECORDER.error("Form failed field validation");

        mView = new ModelAndView();
        mView.addObject(Constants.ERROR_MESSAGE, this.appConfig.getMessageValidationFailed());
        mView.addObject("command", new EmailMessage());
        mView.setViewName(this.appConfig.getContactPage());

        if (DEBUG) {
            DEBUGGER.debug("ModelAndView: {}", mView);
        }

        return mView;
    }

    try {
        EmailUtils.sendEmailMessage(message, true);

        EmailMessage autoResponse = new EmailMessage();
        autoResponse.setIsAlert(false);
        autoResponse.setMessageSubject(this.contactResponseEmail.getSubject());
        autoResponse.setMessageTo(new ArrayList<>(Arrays
                .asList(String.format(this.contactResponseEmail.getTo()[0], message.getEmailAddr().get(0)))));
        autoResponse.setEmailAddr(
                new ArrayList<>(Arrays.asList(String.format(this.contactResponseEmail.getFrom()))));
        autoResponse.setMessageBody(String.format(this.contactResponseEmail.getText(), message.getEmailAddr(),
                message.getMessageBody()));

        if (DEBUG) {
            DEBUGGER.debug("EmailMessage: {}", autoResponse);
        }

        EmailUtils.sendEmailMessage(autoResponse, true);

        mView = new ModelAndView(new RedirectView());
        mView.setViewName(this.appConfig.getRequestCompletePage());
    } catch (MessagingException msx) {
        ERROR_RECORDER.error(msx.getMessage(), msx);

        mView.setViewName(this.appConfig.getErrorResponsePage());
    }

    if (DEBUG) {
        DEBUGGER.debug("ModelAndView: {}", mView);
    }

    return mView;
}

From source file:com.cws.us.pws.controllers.CommonController.java

@RequestMapping(value = "/search", method = RequestMethod.POST)
public final ModelAndView siteSearch(@ModelAttribute("request") final SearchRequest request,
        final BindingResult bindResult) {
    final String methodName = CommonController.CNAME
            + "#sendMessage(@ModelAttribute(\"request\") final SearchRequest request, final BindingResult bindResult)";

    if (DEBUG) {/*from   ww  w .  ja  va2s. com*/
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("SearchRequest: {}", request);
        DEBUGGER.debug("BindingResult: {}", bindResult);
    }

    ModelAndView mView = new ModelAndView();

    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpServletRequest hRequest = requestAttributes.getRequest();
    final HttpSession hSession = hRequest.getSession();
    final ISearchProcessor processor = new SearchProcessorImpl();

    if (DEBUG) {
        DEBUGGER.debug("ServletRequestAttributes: {}", requestAttributes);
        DEBUGGER.debug("HttpServletRequest: {}", hRequest);
        DEBUGGER.debug("HttpSession: {}", hSession);
        DEBUGGER.debug("Session ID: {}", hSession.getId());

        DEBUGGER.debug("Dumping session content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> sessionEnumeration = hSession.getAttributeNames();

        while (sessionEnumeration.hasMoreElements()) {
            String sessionElement = sessionEnumeration.nextElement();
            Object sessionValue = hSession.getAttribute(sessionElement);

            DEBUGGER.debug("Attribute: " + sessionElement + "; Value: " + sessionValue);
        }

        DEBUGGER.debug("Dumping request content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> requestEnumeration = hRequest.getAttributeNames();

        while (requestEnumeration.hasMoreElements()) {
            String requestElement = requestEnumeration.nextElement();
            Object requestValue = hRequest.getAttribute(requestElement);

            DEBUGGER.debug("Attribute: " + requestElement + "; Value: " + requestValue);
        }

        DEBUGGER.debug("Dumping request parameters:");
        @SuppressWarnings("unchecked")
        Enumeration<String> paramsEnumeration = hRequest.getParameterNames();

        while (paramsEnumeration.hasMoreElements()) {
            String requestElement = paramsEnumeration.nextElement();
            Object requestValue = hRequest.getParameter(requestElement);

            DEBUGGER.debug("Parameter: " + requestElement + "; Value: " + requestValue);
        }
    }

    // validate
    this.appConfig.getEmailValidator().validate(request, bindResult);

    if (bindResult.hasErrors()) {
        // errors occurred during validation
        ERROR_RECORDER.error("Form failed field validation");

        mView.addObject(Constants.ERROR_MESSAGE, this.appConfig.getMessageValidationFailed());
        mView.addObject("command", new SearchRequest());
        mView.setViewName(this.appConfig.getSearchRequestPage());

        if (DEBUG) {
            DEBUGGER.debug("ModelAndView: {}", mView);
        }

        return mView;
    }

    try {
        SearchResponse response = processor.doSiteSearch(request);

        if (DEBUG) {
            DEBUGGER.debug("SearchResponse: {}", response);
        }

        if (response.getRequestStatus() == CoreServicesStatus.SUCCESS) {
            mView.addObject("pages", (int) Math.ceil(response.getEntryCount() * 1.0 / this.recordsPerPage));
            mView.addObject("page", 1);
            mView.addObject("searchTerms", request.getSearchTerms());
            mView.addObject("searchResults", response.getResults());
            mView.setViewName(this.appConfig.getSearchRequestPage());
        } else {
            mView.addObject(Constants.MESSAGE_RESPONSE, response.getResponse());
            mView.setViewName(this.appConfig.getSearchRequestPage());
        }

        mView = new ModelAndView(new RedirectView());
        mView.setViewName(this.appConfig.getRequestCompletePage());
    } catch (SearchRequestException srx) {
        ERROR_RECORDER.error(srx.getMessage(), srx);

        mView = new ModelAndView(new RedirectView());
        mView.setViewName(this.appConfig.getErrorResponsePage());
    }

    if (DEBUG) {
        DEBUGGER.debug("ModelAndView: {}", mView);
    }

    return mView;
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractRegistrationController.java

/**
 * Private method to add Fraud Profiling Host To Session
 * //from   ww w.j  av a  2  s .c om
 * @param map
 */
private void addFraudProfilingHostToSession(ModelMap map) {

    // No need to pass profiling API host data unless needed
    DeviceFraudDetectionService deviceFraudDetectionService = (DeviceFraudDetectionService) connectorManagementService
            .getOssServiceInstancebycategory(ConnectorType.DEVICE_FRAUD_CONTROL);
    if (deviceFraudDetectionService == null || !deviceFraudDetectionService.isEnabled()) {
        map.remove("ThreatMetrixEnabled");
        return;
    }

    map.addAttribute("ThreatMetrixEnabled", "True");

    ServletRequestAttributes requestAttrs = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();

    // Add Device profiling parameters
    requestAttrs.getRequest().getSession().setAttribute("fraudProfilingHost", deviceFraudDetectionService
            .getServiceInstanceConfiguration().getInstanceProperties().get("profilinghost").getValue());

    requestAttrs.getRequest().getSession().setAttribute("fraudOrgid", deviceFraudDetectionService
            .getServiceInstanceConfiguration().getInstanceProperties().get("orgid").getValue());
}

From source file:org.bibsonomy.webapp.controller.actions.DeliciousImportController.java

protected String createRedirect(SettingsViewCommand command, RequestWrapperContext context, Errors errors) {

    final DeliciousSignPost oAuth = signPostManager.createDeliciousSignPost();
    final ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    attr.setAttribute(signPostManager.getoAuthKey(), oAuth, ServletRequestAttributes.SCOPE_SESSION);

    try {/*from   www  .j a  v a  2s  .  com*/
        return oAuth.getRequestToken(
                signPostManager.getCallbackBaseUrl() + "?" + "ckey=" + context.getCkey() + "&" + "overwrite="
                        + command.isOverwriteV2() + "&" + "importData=" + command.getImportDataV2());
    } catch (Exception ex) {
        attr.removeAttribute(signPostManager.getoAuthKey(), ServletRequestAttributes.SCOPE_SESSION);
        errors.reject("error.furtherInformations", new Object[] { ex.getMessage() },
                "The following error occurred: {0}");
        log.warn("Delicious-Import failed: " + ex.getMessage());
    }

    return null;
}

From source file:org.bibsonomy.webapp.controller.actions.ImportBookmarksController.java

@Override
public View workOn(final ImportCommand command) {
    final RequestWrapperContext context = command.getContext();

    /*/*from  w w w  . jav a  2  s.  c om*/
     * only users which are logged in might post -> send them to
     * login page
     */
    if (!context.isUserLoggedIn()) {
        throw new AccessDeniedException("please log in");
    }

    final User loginUser = context.getLoginUser();

    /*
     * check credentials to fight CSRF attacks 
     * 
     */
    if (!context.isValidCkey()) {
        errors.reject("error.field.valid.ckey");
        /*
         * FIXME: correct URL?
         * FIXME: don't do this on first call of form!
         */
        return Views.IMPORT;
    }

    if (errors.hasErrors()) {
        return Views.IMPORT;
    }

    List<Post<Bookmark>> posts = new LinkedList<Post<Bookmark>>();
    List<Tag> relations = new LinkedList<Tag>();

    final String importType = command.getImportType();
    try {
        if ("delicious".equals(importType)) {
            /*
             * TODO: we want to have checkboxes, not radio buttons!
             */
            final String importData = command.getImportData();
            /*
             * import posts/bundles from Delicious
             */
            if ("posts".equals(importData)) {
                final RemoteServiceBookmarkImporter importer = importerFactory.getBookmarkImporter();
                importer.setCredentials(command.getUserName(), command.getPassWord());
                posts = importer.getPosts();
            }
            if ("bundles".equals(importData)) {
                final RelationImporter relationImporter = importerFactory.getRelationImporter();
                relationImporter.setCredentials(command.getUserName(), command.getPassWord());
                relations = relationImporter.getRelations();
            }

        } else if ("delicious.yahoo".equals(importType)) {
            /*
             * TODO: we want to have checkboxes, not radio buttons!
             */
            final String importData = command.getImportData();
            final ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
                    .currentRequestAttributes();
            final DeliciousSignPost oAuth = (DeliciousSignPost) attr.getAttribute(signPostManager.getoAuthKey(),
                    ServletRequestAttributes.SCOPE_SESSION);
            attr.removeAttribute(signPostManager.getoAuthKey(), ServletRequestAttributes.SCOPE_SESSION);
            oAuth.getAccessToken(command.getOauth_verifier());
            /*
             * import posts/bundles from Delicious
             */
            if ("posts".equals(importData)) {
                posts = DeliciousV2Importer.getPosts(oAuth.sign(new URL(signPostManager.getBookmarksUrl())));
            }
            if ("bundles".equals(importData)) {
                relations = DeliciousV2Importer
                        .getRelations(oAuth.sign(new URL(signPostManager.getBundlesUrl())));
            }
        } else if ("firefox".equals(importType)) {
            /*
             * import posts/relations from Firefox
             */
            final FileUploadInterface uploadFileHandler = this.uploadFactory.getFileUploadHandler(
                    Collections.singletonList(command.getFile().getFileItem()),
                    FileUploadInterface.firefoxImportExt);
            final Document document = uploadFileHandler.writeUploadedFile();
            /*
             * FileBookmarkImporter interface
             */
            final FileBookmarkImporter fileImporter = new FirefoxImporter();
            fileImporter.initialize(document.getFile(), loginUser, command.getGroup());
            posts = fileImporter.getPosts();
            /*
             * clear temporary file
             */
            document.getFile().delete();
        } else {
            log.info("unknown import type '" + importType + "'");
        }
        /*
         * FIXME: too general error keys!
         */
    } catch (final UnsupportedFileTypeException ex) {
        errors.reject("error.furtherInformations", new Object[] { ex.getMessage() },
                "The following error occurred: {0}");
    } catch (final Exception ex) {
        errors.reject("error.furtherInformations", new Object[] { ex.getMessage() },
                "The following error occurred: {0}");
        log.warn("Delicious/Firefox-Import failed: " + ex.getMessage());
    }

    /** store the posts **/
    if (present(posts)) {
        this.storePosts(command, posts);

        /** how many posts were found? **/
        command.setTotalCount(posts.size());
    }

    /** if available store relations **/
    if (present(relations)) {
        this.storeRelations(relations, command);

        /** how many bundles were found? **/
        command.setTotalCount(relations.size());
    }

    return Views.IMPORT;
}

From source file:org.cloudfoundry.identity.uaa.client.ClientAdminEndpoints.java

private boolean authenticateClient(String clientId, String clientSecret) {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(clientId,
            clientSecret);/*from w  w  w .  j av a  2s.co  m*/
    try {
        HttpServletRequest curRequest = ((ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes()).getRequest();
        if (curRequest != null) {
            authentication.setDetails(new UaaAuthenticationDetails(curRequest, clientId));
        }
    } catch (IllegalStateException x) {
        //ignore - means no thread bound request found
    }
    try {
        Authentication auth = authenticationManager.authenticate(authentication);
        return auth.isAuthenticated();
    } catch (AuthenticationException e) {
        return false;
    } catch (Exception e) {
        logger.debug("Unable to authenticate/validate " + clientId, e);
        return false;
    }
}

From source file:org.cloudfoundry.identity.uaa.login.saml.LoginSamlAuthenticationProvider.java

protected UaaUser createIfMissing(UaaPrincipal samlPrincipal, boolean addNew,
        Collection<? extends GrantedAuthority> authorities, MultiValueMap<String, String> userAttributes) {
    UaaUser user = null;/*from w  w  w  . ja  v  a2  s.  co  m*/
    String invitedUserId = null;
    boolean is_invitation_acceptance = isAcceptedInvitationAuthentication();
    if (is_invitation_acceptance) {
        invitedUserId = (String) RequestContextHolder.currentRequestAttributes().getAttribute("user_id",
                RequestAttributes.SCOPE_SESSION);
        user = userDatabase.retrieveUserById(invitedUserId);
        if (userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME) != null) {
            if (!userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME).equalsIgnoreCase(user.getEmail())) {
                throw new BadCredentialsException(
                        "SAML User email mismatch. Authenticated email doesn't match invited email.");
            }
        } else {
            userAttributes = new LinkedMultiValueMap<>(userAttributes);
            userAttributes.add(EMAIL_ATTRIBUTE_NAME, user.getEmail());
        }
        addNew = false;
        if (user.getUsername().equals(user.getEmail()) && !user.getUsername().equals(samlPrincipal.getName())) {
            user.setVerified(true);
            user = user.modifyUsername(samlPrincipal.getName());
        }
        publish(new InvitedUserAuthenticatedEvent(user));
        user = userDatabase.retrieveUserById(invitedUserId);
    }

    boolean userModified = false;
    UaaUser userWithSamlAttributes = getUser(samlPrincipal, userAttributes);
    try {
        if (user == null) {
            user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
        }
    } catch (UsernameNotFoundException e) {
        if (!addNew) {
            throw new LoginSAMLException("SAML user does not exist. "
                    + "You can correct this by creating a shadow user for the SAML user.", e);
        }
        // Register new users automatically
        publish(new NewUserAuthenticatedEvent(userWithSamlAttributes));
        try {
            user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
        } catch (UsernameNotFoundException ex) {
            throw new BadCredentialsException(
                    "Unable to establish shadow user for SAML user:" + samlPrincipal.getName());
        }
    }
    if (haveUserAttributesChanged(user, userWithSamlAttributes)) {
        userModified = true;
        user = user.modifyAttributes(userWithSamlAttributes.getEmail(), userWithSamlAttributes.getGivenName(),
                userWithSamlAttributes.getFamilyName(), userWithSamlAttributes.getPhoneNumber());
    }
    publish(new ExternalGroupAuthorizationEvent(user, userModified, authorities, true));
    user = userDatabase.retrieveUserById(user.getId());
    UaaPrincipal result = new UaaPrincipal(user);
    Authentication success = new UaaAuthentication(result, user.getAuthorities(), null);
    publish(new UserAuthenticationSuccessEvent(user, success));
    return user;
}

From source file:org.cloudfoundry.identity.uaa.login.saml.LoginSamlAuthenticationProvider.java

protected boolean isAcceptedInvitationAuthentication() {
    try {// ww w.j  av  a  2s  . c  o m
        RequestAttributes attr = RequestContextHolder.currentRequestAttributes();
        if (attr != null) {
            Boolean result = (Boolean) attr.getAttribute("IS_INVITE_ACCEPTANCE",
                    RequestAttributes.SCOPE_SESSION);
            if (result != null) {
                return result.booleanValue();
            }
        }
    } catch (IllegalStateException x) {
        //nothing bound on thread.
        logger.debug("Unable to retrieve request attributes during SAML authentication.");

    }
    return false;
}

From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManager.java

@Override
protected UaaUser userAuthenticated(Authentication request, UaaUser userFromRequest, UaaUser userFromDb) {
    boolean userModified = false;
    boolean is_invitation_acceptance = isAcceptedInvitationAuthentication();
    String email = userFromRequest.getEmail();
    logger.debug("XOAUTH user authenticated:" + email);
    if (is_invitation_acceptance) {
        String invitedUserId = (String) RequestContextHolder.currentRequestAttributes().getAttribute("user_id",
                RequestAttributes.SCOPE_SESSION);
        logger.debug("XOAUTH user accepted invitation, user_id:" + invitedUserId);
        userFromDb = getUserDatabase().retrieveUserById(invitedUserId);
        if (email != null) {
            if (!email.equalsIgnoreCase(userFromDb.getEmail())) {
                throw new BadCredentialsException(
                        "OAuth User email mismatch. Authenticated email doesn't match invited email.");
            }/*ww  w .j  a va2  s.  co m*/
        }
        publish(new InvitedUserAuthenticatedEvent(userFromDb));
        userFromDb = getUserDatabase().retrieveUserById(invitedUserId);
    }

    //we must check and see if the email address has changed between authentications
    if (request.getPrincipal() != null) {
        if (haveUserAttributesChanged(userFromDb, userFromRequest)) {
            logger.debug("User attributed have changed, updating them.");
            userFromDb = userFromDb.modifyAttributes(email, userFromRequest.getGivenName(),
                    userFromRequest.getFamilyName(), userFromRequest.getPhoneNumber())
                    .modifyUsername(userFromRequest.getUsername());
            userModified = true;
        }
    }
    ExternalGroupAuthorizationEvent event = new ExternalGroupAuthorizationEvent(userFromDb, userModified,
            userFromRequest.getAuthorities(), true);
    publish(event);
    return getUserDatabase().retrieveUserById(userFromDb.getId());
}

From source file:org.cloudfoundry.identity.uaa.provider.saml.LoginSamlAuthenticationProvider.java

protected UaaUser createIfMissing(UaaPrincipal samlPrincipal, boolean addNew,
        Collection<? extends GrantedAuthority> authorities, MultiValueMap<String, String> userAttributes) {
    UaaUser user = null;//w  w w .ja  v  a2s .c o  m
    String invitedUserId = null;
    boolean is_invitation_acceptance = isAcceptedInvitationAuthentication();
    if (is_invitation_acceptance) {
        invitedUserId = (String) RequestContextHolder.currentRequestAttributes().getAttribute("user_id",
                RequestAttributes.SCOPE_SESSION);
        user = userDatabase.retrieveUserById(invitedUserId);
        if (userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME) != null) {
            if (!userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME).equalsIgnoreCase(user.getEmail())) {
                throw new BadCredentialsException(
                        "SAML User email mismatch. Authenticated email doesn't match invited email.");
            }
        } else {
            userAttributes = new LinkedMultiValueMap<>(userAttributes);
            userAttributes.add(EMAIL_ATTRIBUTE_NAME, user.getEmail());
        }
        addNew = false;
        if (user.getUsername().equals(user.getEmail()) && !user.getUsername().equals(samlPrincipal.getName())) {
            user.setVerified(true);
            user = user.modifyUsername(samlPrincipal.getName());
        }
        publish(new InvitedUserAuthenticatedEvent(user));
        user = userDatabase.retrieveUserById(invitedUserId);
    }

    boolean userModified = false;
    UaaUser userWithSamlAttributes = getUser(samlPrincipal, userAttributes);
    try {
        if (user == null) {
            user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
        }
    } catch (UsernameNotFoundException e) {
        UaaUser uaaUser = userDatabase.retrieveUserByEmail(userWithSamlAttributes.getEmail(),
                samlPrincipal.getOrigin());
        if (uaaUser != null) {
            user = uaaUser.modifyUsername(samlPrincipal.getName());
        } else {
            if (!addNew) {
                throw new LoginSAMLException("SAML user does not exist. "
                        + "You can correct this by creating a shadow user for the SAML user.", e);
            }
            // Register new users automatically
            publish(new NewUserAuthenticatedEvent(userWithSamlAttributes));
            try {
                user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
            } catch (UsernameNotFoundException ex) {
                throw new BadCredentialsException(
                        "Unable to establish shadow user for SAML user:" + samlPrincipal.getName());
            }
        }
    }
    if (haveUserAttributesChanged(user, userWithSamlAttributes)) {
        userModified = true;
        user = user.modifyAttributes(userWithSamlAttributes.getEmail(), userWithSamlAttributes.getGivenName(),
                userWithSamlAttributes.getFamilyName(), userWithSamlAttributes.getPhoneNumber());
    }
    publish(new ExternalGroupAuthorizationEvent(user, userModified, authorities, true));
    user = userDatabase.retrieveUserById(user.getId());
    UaaPrincipal result = new UaaPrincipal(user);
    Authentication success = new UaaAuthentication(result, user.getAuthorities(), null);
    publish(new UserAuthenticationSuccessEvent(user, success));
    return user;
}