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.telefonica.euro_iaas.sdc.rest.auth.OpenStackAuthenticationFilter.java

/**
 * (non-Javadoc) @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 * javax.servlet.FilterChain)./*from   w ww  . j  av a2s. c  o m*/
 */
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();

    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    String header = request.getHeader(OPENSTACK_HEADER_TOKEN);
    String pathInfo = request.getPathInfo();
    logger.debug(header);
    logger.debug(pathInfo);

    MDC.put("txId", ((HttpServletRequest) req).getSession().getId());

    if (pathInfo != null && (pathInfo.equals("/") || pathInfo.equals("/extensions"))) {
        /**
         * It is not needed to authenticate these operations
         */
        logger.debug("Operation does not need to Authenticate");
    } else {

        if (header == null) {
            header = "";
        }

        try {
            String token = header;
            if ("".equals(token)) {
                String str = "Missing token header";
                logger.info(str);
                throw new BadCredentialsException(str);
            }
            String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID);
            String txId = request.getHeader("txId");
            if (txId != null) {
                MDC.put("txId", txId);

            }

            logger.debug(tenantId);
            logger.debug(token);
            // String tenantId = request.getPathInfo().split("/")[3];

            if (debug) {
                logger.debug("OpenStack Authentication Authorization header " + "found for user '" + token
                        + "' and tenant " + tenantId);
            }

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(token,
                    tenantId);
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authResult = authenticationManager.authenticate(authRequest);

            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }

            // check AUTH-TOKEN and VDC are the same
            String uri = request.getRequestURI();
            logger.debug("URI: " + uri);
            if (uri.contains("vdc") && !uri.contains(tenantId)) {
                String str = "Bad credentials for requested VDC";
                logger.info(str);
                throw new AccessDeniedException(str);
            }

            UserDetails user = (UserDetails) authResult.getPrincipal();
            logger.debug("User: " + user.getUsername());
            logger.debug("Token: " + user.getPassword());
            if (authResult.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(authRequest);

            }

            // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL");

            rememberMeServices.loginSuccess(request, response, authResult);

            onSuccessfulAuthentication(request, response, authResult);

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

            if (debug) {
                logger.debug("Authentication request for failed: " + failed);
            }

            rememberMeServices.loginFail(request, response);
            onUnsuccessfulAuthentication(request, response, failed);

            if (ignoreFailure) {
                chain.doFilter(request, response);
            } else {
                authenticationEntryPoint.commence(request, response, failed);
            }

            return;
        } catch (AccessDeniedException ex) {
            throw ex;
        } catch (Exception ex) {
            SecurityContextHolder.clearContext();

            if (debug) {
                logger.debug("Authentication exception: " + ex);
            }

            rememberMeServices.loginFail(request, response);

            if (ignoreFailure) {
                chain.doFilter(request, response);
            } else {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            }
            return;
        }

        String keystoneURL = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL);

        response.addHeader("Www-Authenticate", "Keystone uri='" + keystoneURL + "'");
    }

    // TODO jesuspg: question:add APIException
    chain.doFilter(request, response);

}

From source file:com.haulmont.restapi.auth.CubaUserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    String ipAddress = request.getRemoteAddr();

    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        RestApiConfig config = configuration.getConfig(RestApiConfig.class);
        if (!config.getStandardAuthenticationEnabled()) {
            log.debug(/*from  w  ww. j a  va  2 s  . c  om*/
                    "Standard authentication is disabled. Property cuba.rest.standardAuthenticationEnabled is false");

            throw new InvalidGrantException("Authentication disabled");
        }

        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

        String login = (String) token.getPrincipal();

        UserSession session;
        try {
            String passwordHash = passwordEncryption.getPlainHash((String) token.getCredentials());

            LoginPasswordCredentials credentials = new LoginPasswordCredentials(login, passwordHash);
            credentials.setIpAddress(ipAddress);
            credentials.setClientType(ClientType.REST_API);
            credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));

            //if the locale value is explicitly passed in the Accept-Language header then set its value to the
            //credentials. Otherwise, the locale of the user should be used
            Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request);
            if (locale != null) {
                credentials.setLocale(locale);
                credentials.setOverrideLocale(true);
            } else {
                credentials.setOverrideLocale(false);
            }

            session = authenticationService.login(credentials).getSession();
        } catch (AccountLockedException le) {
            log.info("Blocked user login attempt: login={}, ip={}", login, ipAddress);
            throw new LockedException("User temporarily blocked");
        } catch (RestApiAccessDeniedException ex) {
            log.info("User is not allowed to use the REST API {}", login);
            throw new BadCredentialsException("User is not allowed to use the REST API");
        } catch (LoginException e) {
            log.info("REST API authentication failed: {} {}", login, ipAddress);
            throw new BadCredentialsException("Bad credentials");
        }

        AppContext.setSecurityContext(new SecurityContext(session));

        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
                authentication.getPrincipal(), authentication.getCredentials(),
                getRoleUserAuthorities(authentication));
        @SuppressWarnings("unchecked")
        Map<String, String> details = (Map<String, String>) authentication.getDetails();
        details.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString());
        result.setDetails(details);
        return result;
    }

    return null;
}

From source file:org.artifactory.ui.rest.service.admin.security.auth.login.LoginService.java

/**
 * authenticate credential against Security providers (Artifactory,Ldap , crown and etc)
 * @param authenticationToken - user credentials
 * @param artifactoryContext - artifactory web context
 * @param artifactoryRestRequest - encapsulate data related to request
 * @param artifactoryRestResponse - encapsulate data related to response
 * @return Authentication Data// w w w .j av  a2s  . c o  m
 */
private Authentication authenticateCredential(UsernamePasswordAuthenticationToken authenticationToken,
        ArtifactoryContext artifactoryContext, ArtifactoryRestRequest artifactoryRestRequest,
        RestResponse artifactoryRestResponse) {
    WebAuthenticationDetails details = new UiAuthenticationDetails(artifactoryRestRequest.getServletRequest(),
            artifactoryRestResponse.getServletResponse());
    authenticationToken.setDetails(details);
    AuthenticationManager authenticationManager = (AuthenticationManager) artifactoryContext
            .getBean("authenticationManager");
    Authentication authentication = authenticationManager.authenticate(authenticationToken);
    return authentication;
}

From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationFilter.java

/**
 * (non-Javadoc) @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 * javax.servlet.FilterChain).//from  w w w  .j  a v a  2 s. c  om
 */
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();

    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    String headerToken = request.getHeader(OPENSTACK_HEADER_TOKEN);
    String pathInfo = request.getPathInfo();
    logger.debug(headerToken);
    logger.debug(pathInfo);

    // first of all, check HTTP if exists accept header
    if (!validateAcceptHeader(request, response)) {
        return;
    }

    MDC.put("txId", ((HttpServletRequest) req).getSession().getId());

    if (pathInfo != null && (pathInfo.equals("/") || pathInfo.equals("/extensions"))) {
        /**
         * It is not needed to authenticate these operations
         */
        logger.debug("Operation does not need to Authenticate");
    } else {

        if (headerToken == null) {
            headerToken = "";
        }

        try {
            String token = headerToken;
            if ("".equals(token)) {
                String str = "Missing token header";
                logger.info(str);
                throw new BadCredentialsException(str);
            }
            String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID);
            logger.debug(tenantId);
            logger.debug(token);
            // String tenantId = request.getPathInfo().split("/")[3];

            if (debug) {
                logger.debug("OpenStack Authentication Authorization header " + "found for user '" + token
                        + "' and tenant " + tenantId);
            }

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(token,
                    tenantId);
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authResult = authenticationManager.authenticate(authRequest);

            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }

            // check AUTH-TOKEN and VDC are the same
            String uri = request.getRequestURI();
            logger.debug("URI: " + uri);
            if (uri.contains("vdc") && !uri.contains(tenantId)) {
                String str = "Bad credentials for requested VDC";
                logger.info(str);
                throw new AccessDeniedException(str);
            }

            UserDetails user = (UserDetails) authResult.getPrincipal();

            logger.debug("User: " + user.getUsername());
            logger.debug("Token: " + user.getPassword());
            if (authResult.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(authRequest);

            }

            // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL");

            rememberMeServices.loginSuccess(request, response, authResult);

            onSuccessfulAuthentication(request, response, authResult);

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

            if (debug) {
                logger.debug("Authentication request for failed: " + failed);
            }

            rememberMeServices.loginFail(request, response);
            onUnsuccessfulAuthentication(request, response, failed);

            if (ignoreFailure) {
                chain.doFilter(request, response);
            } else {
                authenticationEntryPoint.commence(request, response, failed);
            }

            return;
        } catch (AccessDeniedException ex) {
            throw ex;
        } catch (Exception ex) {
            SecurityContextHolder.clearContext();

            if (debug) {
                logger.debug("Authentication exception: " + ex);
            }

            rememberMeServices.loginFail(request, response);

            if (ignoreFailure) {
                chain.doFilter(request, response);
            } else {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            }
            return;
        }

        String keystoneURL = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL);

        response.addHeader("Www-Authenticate", "Keystone uri='" + keystoneURL + "'");
    }

    // TODO jesuspg: question:add APIException
    chain.doFilter(request, response);

}

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();/*from  w  w  w.  j  a  v  a  2  s .c  o  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.zanshang.controllers.web.RegisterController.java

private void authenticateUser(String username, String password, HttpServletRequest request) {
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
    token.setDetails(new WebAuthenticationDetails(request));
    Authentication authenticatedUser = authenticationManager.authenticate(token);
    token.setDetails(new WebAuthenticationDetails(request));
    SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
}

From source file:com.amediamanager.service.UserServiceImpl.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
    String username = String.valueOf(auth.getPrincipal());
    String password = String.valueOf(auth.getCredentials());

    User user = find(username);/* ww w .  j a v  a  2s . c  o  m*/

    if (null == user || (!BCrypt.checkpw(password, user.getPassword()))) {
        throw new BadCredentialsException("Invalid username or password");
    }

    List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
    grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));

    // Create new auth token
    auth = new UsernamePasswordAuthenticationToken(username, null, grantedAuths);
    auth.setDetails(user);
    return auth;
}

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 .  co 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;
}