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.jd.survey.web.security.AccountController.java

/**
 * Updates  logged in user password/*from  w  w  w . j a  v  a  2  s .c  o m*/
 * @param oldPassword
 * @param newPassword
 * @param newPasswordConfirm
 * @param proceed
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/rpass", method = RequestMethod.POST, produces = "text/html")
public String updatePasswordPost(@RequestParam(value = "password", required = true) String oldPassword,
        @RequestParam(value = "nPassword", required = true) String newPassword,
        @RequestParam(value = "cPassword", required = true) String newPasswordConfirm,
        @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    try {
        if (proceed != null) {

            //check that the old password is correct
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    principal.getName(), oldPassword);
            authenticationToken.setDetails(new WebAuthenticationDetails(httpServletRequest));
            try {
                Authentication auth = authenticationManager.authenticate(authenticationToken);
                if (auth == null || !auth.isAuthenticated()) {
                    //invalid password enetered
                    uiModel.asMap().clear();
                    uiModel.addAttribute("status", "E"); //Unmatching Passwords
                    return "account/rpass";
                }

            } catch (AuthenticationException e) {
                uiModel.asMap().clear();
                uiModel.addAttribute("status", "E"); //Unmatching Passwords
                return "account/rpass";
            }
            //Check new password strenght 
            if (!GenericValidator.matchRegexp(newPassword, globalSettings.getPasswordEnforcementRegex())) {
                uiModel.asMap().clear();
                uiModel.addAttribute("status", "I"); //Unmatching Passwords
                return "account/rpass";
            }
            //check that passwords match    
            if (!newPassword.equals(newPasswordConfirm)) {
                uiModel.asMap().clear();

                uiModel.addAttribute("status", "U"); //Unmatching Passwords
                return "account/rpass";
            }
            User loggedInUser = userService.user_findByLogin(principal.getName());
            //All validations passed, save the HASH of the password in the database
            loggedInUser.setPassword(newPassword);
            userService.user_updatePassword(loggedInUser);
            uiModel.addAttribute("status", "S");//success
            return "account/rpass";
        } else {
            return "redirect:/account/show";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:org.cloudfoundry.identity.uaa.social.SocialClientAuthenticationFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    SocialClientUserDetails user = socialClientUserDetailsSource.getUserDetails();
    Collection<GrantedAuthority> authorities = user.getAuthorities();
    UsernamePasswordAuthenticationToken result;
    if (authorities != null && !authorities.isEmpty()) { // TODO: correlate user data with existing accounts if email or username missing
        result = new UsernamePasswordAuthenticationToken(user, null, authorities);
    } else {//ww w.  j  a v a 2  s. co m
        // Unauthenticated
        result = new UsernamePasswordAuthenticationToken(user, null);
    }
    result.setDetails(authenticationDetailsSource.buildDetails(request));
    return result;
}

From source file:org.apache.cxf.fediz.service.idp.STSUPAuthenticationProvider.java

private Authentication handleUsernamePassword(UsernamePasswordAuthenticationToken usernamePasswordToken,
        IdpSTSClient sts) {//from   w ww .j  a  va  2s .  c o m
    sts.getProperties().put(SecurityConstants.USERNAME, usernamePasswordToken.getName());
    sts.getProperties().put(SecurityConstants.PASSWORD, (String) usernamePasswordToken.getCredentials());

    try {

        // Line below may be uncommented for debugging    
        // setTimeout(sts.getClient(), 3600000L);

        SecurityToken token = sts.requestSecurityToken(this.appliesTo);

        List<GrantedAuthority> authorities = createAuthorities(token);

        UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(
                usernamePasswordToken.getName(), usernamePasswordToken.getCredentials(), authorities);

        STSUserDetails details = new STSUserDetails(usernamePasswordToken.getName(),
                (String) usernamePasswordToken.getCredentials(), authorities, token);
        upat.setDetails(details);

        LOG.debug("[IDP_TOKEN={}] provided for user '{}'", token.getId(), usernamePasswordToken.getName());
        return upat;

    } catch (Exception ex) {
        LOG.info("Failed to authenticate user '" + usernamePasswordToken.getName() + "'", ex);
        return null;
    }

}

From source file:it.smartcommunitylab.tocati.controller.UserAuthController.java

@RequestMapping("/{ownerId}/userloginevway")
public @ResponseBody UserData loginEVWay(@PathVariable String ownerId, @RequestParam String email,
        @RequestParam String password, @RequestParam String language, HttpServletRequest request,
        HttpServletResponse response) throws IOException, UnauthorizedException {
    //      if(!Utils.validateAPIRequest(request, dataSetSetup, storageManager)) {
    //         throw new UnauthorizedException("Unauthorized Exception: token not valid");
    //      }/*from   w  w  w. ja v  a 2  s .c  om*/
    if (logger.isInfoEnabled()) {
        logger.info(String.format("loginEVWay[%s] login: %s", ownerId, email));
    }

    try {
        UserData userData = evwayAuth.login(email, password, language);
        if (userData == null) {
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            return null;
        }

        userData.setOwnerId(ownerId);
        userData.setDisplayName(email);

        Criteria criteria = Criteria.where("userId").is(userData.getUserId());
        UserData userDB = storageManager.findOneData(UserData.class, criteria, userData.getOwnerId());
        if (userDB == null) {
            userData.setObjectId(Utils.getUUID());
            userData = storageManager.addUser(userData);
        } else {
            userData = userDB;
        }

        LoginData loginData = new LoginData(email, userData.getUserId(), null);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(email, loginData,
                AppUserDetails.TOCATI_AUTHORITIES);

        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authenticatedUser = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authenticatedUser);

        return userData;

    } catch (Exception e) {
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
}

From source file:org.xaloon.wicket.security.spring.SpringSecurityFacade.java

private AuthenticationToken authenticateInternal(AbstractAuthenticationToken authenticationRequestToken) {
    boolean authenticated = false;
    String name = authenticationRequestToken.getName();
    String errorMessage = null;//  w w w. j  a  va 2 s .  com
    try {
        Authentication authentication = authenticationManager.authenticate(authenticationRequestToken);
        authenticated = authentication.isAuthenticated();
        if (authenticated && authentication.getDetails() == null) {
            // Try to load user details. Copy information into new token
            UsernamePasswordAuthenticationToken authenticationWithDetails = new UsernamePasswordAuthenticationToken(
                    authentication.getPrincipal(), authentication.getCredentials(),
                    authentication.getAuthorities());
            authenticationWithDetails.setDetails(userDao.getUserByUsername(authentication.getName()));
            authentication = authenticationWithDetails;
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
        name = authentication.getName();
    } catch (AuthenticationException e) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("User " + name + " failed to login. Reason: ", e);
        }
        authenticated = false;
        errorMessage = e.getMessage();
    }
    if (authenticated) {
        return new AuthenticationToken(name, new ArrayList<AuthenticationAttribute>());
    }
    return new AuthenticationToken(name, errorMessage);
}

From source file:com.telefonica.euro_iaas.sdc.puppetwrapper.auth.OpenStackAuthenticationFilter.java

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

    final boolean info = logger.isInfoEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

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

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

    if (pathInfo.equals("/") || pathInfo.equals("/extensions")) {
        /**/* w  ww. ja  v  a2  s  .  com*/
         * It is not needed to authenticate these operations
         */
        logger.info("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);

            }

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

            if (info) {
                logger.info("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 (info) {
                logger.info("Authentication success: " + authResult);
            }

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

            logger.info("User: " + user.getUsername());
            logger.info("Token: " + user.getToken());
            logger.info("Tenant: " + user.getTenantId());
            logger.info("TenantName - Org: " + user.getTenantName());

            SecurityContextHolder.getContext().setAuthentication(authResult);
            // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL");

            rememberMeServices.loginSuccess(request, response, authResult);

            onSuccessfulAuthentication(request, response, authResult);

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

            if (info) {
                logger.info("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;
        }

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

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

}

From source file:com.px100systems.data.browser.controller.MainController.java

public void autoLogin(HttpServletRequest request, String username, String password) {
    List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority(DbBrowserUserDetailsService.DEFAULT_AUTHORITY));

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password,
            authorities);/*  w ww  .j  a v a  2  s .c  o  m*/
    request.getSession();
    token.setDetails(new WebAuthenticationDetails(request));
    Authentication authenticatedUser = authenticationManager.authenticate(token);
    SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
    HttpSession session = request.getSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());
    session.setAttribute(USER_ATTRIBUTE, username);
}

From source file:org.cloudfoundry.identity.uaa.login.ChainedAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication == null) {
        return authentication;
    }/*from  www .j  a va2s  .co  m*/
    UsernamePasswordAuthenticationToken output = null;
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        output = (UsernamePasswordAuthenticationToken) authentication;
    } else {
        output = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), authentication.getAuthorities());
        output.setAuthenticated(authentication.isAuthenticated());
        output.setDetails(authentication.getDetails());
    }
    boolean authenticated = false;
    Authentication auth = null;
    AuthenticationException lastException = null;
    for (int i = 0; i < delegates.length && (!authenticated); i++) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Attempting chained authentication of " + output + " with manager:" + delegates[i]);
            }
            auth = delegates[i].authenticate(output);
            authenticated = auth.isAuthenticated();
        } catch (AuthenticationException x) {
            if (logger.isDebugEnabled()) {
                logger.debug("Chained authentication exception:", x);
            }
            lastException = x;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Chained Authentication status of " + output + " with manager:" + delegates[i]
                    + "; Authenticated:" + authenticated);
        }
    }
    if (authenticated) {
        return auth;
    } else if (lastException != null) {
        //we had at least one authentication exception, throw it
        throw lastException;
    } else {
        //not authenticated, but return the last of the result
        return auth;
    }
}

From source file:com.sshdemo.common.security.manage.service.UserService.java

protected Authentication createNewAuthentication(UserDetails userDetails, String newPassword) {
    UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(userDetails,
            userDetails.getPassword(), userDetails.getAuthorities());
    newAuthentication.setDetails(userDetails);
    return newAuthentication;
}