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

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

Introduction

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

Prototype

Object getCredentials();

Source Link

Document

The credentials that prove the principal is correct.

Usage

From source file:it.scoppelletti.programmerpower.web.security.SsoAuthenticationFilter.java

/**
 * Implementazione dell’autenticazione.
 * /*  w  w  w.j a va  2  s  .c  o  m*/
 * @param  req  Richiesta.
 * @param  resp Risposta.
 * @return      Token autenticato. Se l’autenticazione non avviene,
 *              restituisce {@code null}.
 */
@Override
public Authentication attemptAuthentication(final HttpServletRequest req, final HttpServletResponse resp)
        throws AuthenticationException, IOException {
    String ticket;
    Authentication result;

    if (myCasClient == null) {
        throw new PropertyNotSetException(toString(), "casClient");
    }

    result = super.attemptAuthentication(req, resp);
    if (result == null) {
        return null;
    }

    ticket = (String) result.getCredentials();
    myCasClient.addAuthenticatedSession(ticket, req.getSession(true));

    return result;
}

From source file:nl.surfnet.spring.security.opensaml.SAMLResponseAuthenticationProvider.java

public Authentication authenticate(Authentication submitted) throws AuthenticationException {

    logger.debug("attempting to authenticate: {}", submitted);

    UserDetails user = assertionConsumer.consume((Response) submitted.getPrincipal());

    SAMLAuthenticationToken authenticated = new SAMLAuthenticationToken(user,
            (String) submitted.getCredentials(), user.getAuthorities());

    authenticated.setDetails(submitted.getDetails());

    logger.debug("Returning with authentication token of {}", authenticated);

    return authenticated;

}

From source file:org.dspace.rest.authentication.DSpaceAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Context context = null;// w w w.  j a v a2 s  .co m

    try {
        context = new Context();
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        HttpServletRequest httpServletRequest = new DSpace().getRequestService().getCurrentRequest()
                .getHttpServletRequest();
        List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>();

        int implicitStatus = authenticationService.authenticateImplicit(context, null, null, null,
                httpServletRequest);

        if (implicitStatus == AuthenticationMethod.SUCCESS) {
            log.info(LogManager.getHeader(context, "login", "type=implicit"));
            addSpecialGroupsToGrantedAuthorityList(context, httpServletRequest, grantedAuthorities);
            return createAuthenticationToken(password, context, grantedAuthorities);

        } else {
            int authenticateResult = authenticationService.authenticate(context, name, password, null,
                    httpServletRequest);
            if (AuthenticationMethod.SUCCESS == authenticateResult) {
                addSpecialGroupsToGrantedAuthorityList(context, httpServletRequest, grantedAuthorities);

                log.info(LogManager.getHeader(context, "login", "type=explicit"));

                return createAuthenticationToken(password, context, grantedAuthorities);

            } else {
                log.info(LogManager.getHeader(context, "failed_login",
                        "email=" + name + ", result=" + authenticateResult));
                throw new BadCredentialsException("Login failed");
            }
        }
    } catch (BadCredentialsException e) {
        throw e;
    } catch (Exception e) {
        log.error("Error while authenticating in the rest api", e);
    } finally {
        if (context != null && context.isValid()) {
            try {
                context.complete();
            } catch (SQLException e) {
                log.error(e.getMessage() + " occurred while trying to close", e);
            }
        }
    }

    return null;
}

From source file:com.github.cherimojava.orchidae.security.MongoAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    LOG.info(AUTH, "login attempt for user {}", authentication.getName());
    UserDetails details = userDetailsService.loadUserByUsername((String) authentication.getPrincipal());

    if (details == null
            || !pwEncoder.matches((String) authentication.getCredentials(), details.getPassword())) {
        LOG.info(AUTH, "failed to authenticate user {}", authentication.getName());
        throw new BadCredentialsException(ERROR_MSG);
    }/* ww w  . j a va 2s.c o  m*/

    LOG.info(AUTH, "login attempt for user {}", authentication.getName());

    return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
            authentication.getCredentials(), details.getAuthorities());
}

From source file:com.github.sshw.security.SSHAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    SSHSession sshSession = new SSHSessionImpl();
    //UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) authentication;
    String username = authentication.getPrincipal().toString();
    String password = authentication.getCredentials().toString();
    //log.info("{}:{}", username, password);
    boolean success = sshSession.login(username, password);
    log.info("SSH login: {}={}", username, success);
    Authentication result = new UsernamePasswordAuthenticationToken(username, password, authorities);
    //result.setAuthenticated(success);
    log.info("adding SSH session for {}", username);
    sshSessionManager.sessionsByUsername.put(username, sshSession);
    return result;
}

From source file:com.spfsolutions.ioms.auth.UserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    try {//w w w. ja va2 s .c  o m
        UserEntity userEntity = userDao.queryForFirst(
                userDao.queryBuilder().where().eq("Username", authentication.getName()).prepare());

        String inputHash = MD5.encrypt(authentication.getCredentials().toString());
        if (userEntity == null || !userEntity.getPassword().equals(inputHash)) {
            throw new BadCredentialsException("Username or password incorrect.");
        } else if (!userEntity.isEnabled()) {
            throw new DisabledException("The username is disabled. Please contact your System Administrator.");
        }
        userEntity.setLastSuccessfulLogon(new DateTime(DateTimeZone.UTC).toDate());

        userDao.createOrUpdate(userEntity);

        Collection<SimpleGrantedAuthority> authorities = buildRolesFromUser(userEntity);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                authentication.getName(), authentication.getCredentials(), authorities);

        return token;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        userDao.getConnectionSource().closeQuietly();
    }
    return null;

}

From source file:com.relecotech.common.controller.AcceptParameterController.java

@RequestMapping(value = "/{name}", method = RequestMethod.GET)
//public String getMovie(@PathVariable String name, ModelMap model) {
public @ResponseBody ModelAndView getParameter(@PathVariable String name) throws ParserConfigurationException {
    //String param =name;
    try {// ww  w  . ja v a 2  s .  c  om
        Map<String, String> valueMap = new HashMap<String, String>();
        String[] data = name.split("&");
        for (String str : data) {
            String[] mapPair = str.split("=");
            valueMap.put(mapPair[0], mapPair[1]);
        }
        String logoutUrl = "https://" + valueMap.get("URL") + ".com";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SAMLCredential credential = (SAMLCredential) authentication.getCredentials();
        TimeZone timeZone = TimeZone.getTimeZone(valueMap.get("timeZone").replace("*", "/"));

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm a");
        dateFormat.setTimeZone(timeZone);

        Calendar calobj = Calendar.getInstance(timeZone);
        String SystemCurrentTime = dateFormat.format(calobj.getTime());
        Date SystemCurrentDateTime = dateFormat.parse(SystemCurrentTime);
        // Date SystemCurrentDateTime = calobj.getTime();

        //SFDC Meeting DATE/TIME 
        String sfdcMeetingTime = valueMap.get("d").replace("*", "/");
        System.out.println("sfdcMeetingTime=" + sfdcMeetingTime);
        Date sfdcMeetingDateTime = dateFormat.parse(sfdcMeetingTime);
        //TIME Before Meeting can satarted 
        Date sfdcMeetingBeforeDateTime = dateFormat
                .parse(AddSubtractTime.getSubtractedTime(sfdcMeetingTime, timeZone));
        //TIME after Meeting cannot be satarted 
        Date sfdcMeetingAfterDateTime = dateFormat
                .parse(AddSubtractTime.getAddedTime(sfdcMeetingTime, timeZone));

        System.out.println("SystemCurrentDateTime=" + SystemCurrentDateTime);
        System.out.println("sfdcMeetingDateTime=" + sfdcMeetingDateTime);
        System.out.println("sfdcMeetingAfterDateTime=" + sfdcMeetingAfterDateTime);
        System.out.println("sfdcMeetingBeforeDateTime=" + sfdcMeetingBeforeDateTime);
        if (SystemCurrentDateTime.after(sfdcMeetingBeforeDateTime)
                && SystemCurrentDateTime.before(sfdcMeetingAfterDateTime)) {
            APIGenerator aPIGenerator = new APIGenerator();
            System.out.println("converted id=" + SalesforceIDConverter.convertID(valueMap.get("code")));
            System.out.println((credential.getAttributeAsString("ContactId")));
            if (valueMap.get("code")
                    .matches(SalesforceIDConverter.convertID(credential.getAttributeAsString("ContactId")))) {

                System.out.println("valuemap=" + valueMap);

                System.out.println("logout url=" + logoutUrl);
                String create = "attendeePW=ap" + "&meetingID=" + valueMap.get("name") + "&moderatorPW=newuser"
                        + "&name=" + valueMap.get("name") + "&logoutURL=" + logoutUrl;
                System.out.println("create parameter=" + create);
                XmlParser.runAPI(aPIGenerator.createAPI("create", create));
                // String join = "fullName=" + valueMap.get("fullName") + "&meetingID=" + valueMap.get("meetingID") + "&password=newuser";
                String join = "fullName=" + credential.getAttributeAsString("username") + "&meetingID="
                        + valueMap.get("name") + "&password=newuser";
                System.out.println("joinparam=" + join);
                aPIGenerator.createAPI("join", join);
                return new ModelAndView("redirect:" + aPIGenerator.apiWithChecksum);

            } else {
                Map<String, String> responceMap = XmlParser.runAPI(
                        aPIGenerator.createAPI("isMeetingRunning", "meetingID=" + valueMap.get("name")));
                String join = "fullName=" + credential.getAttributeAsString("username") + "&meetingID="
                        + valueMap.get("name") + "&password=ap";
                if (responceMap.get("running").matches("true")) {

                    aPIGenerator.createAPI("join", join);
                    return new ModelAndView("redirect:" + aPIGenerator.apiWithChecksum);
                } else {
                    String student = "<center>  <h1>Wait! Presenter has not joined meeting yet!</h1>\n"
                            //                                +"<img src=\"${pageContext.request.contextPath}/images/bbbtime.jpg\" style=\"width:304px;height:228px\"/> "
                            + "     <h2>\n" + "           Please try after few minutes.\n" + "        \n"
                            + "<br>Meeting Date/Time:" + dateFormat.format(sfdcMeetingDateTime) + "<br><a href="
                            + logoutUrl + ">Back</a>" + "    </h2></center> ";
                    // return new ModelAndView("redirect:" + "/student.jsp");
                    return new ModelAndView("student", "student", student);
                }
            }

        } else {
            //                
            if (SystemCurrentDateTime.compareTo(sfdcMeetingDateTime) == -1) {

                String wait = "<center> <h1>Too Early for Meeting!</h1><br></center>\n"
                        //                             +"<img src=\"${pageContext.request.contextPath}/images/bbbtime.jpg\" style=\"width:304px;height:228px\"/> "
                        + "  <center>  <h2>Meeting is not yet open.<br>\n"
                        + "  Please check meeting schedule time. \n<br>" + "<br>Meeting Date/Time:"
                        + dateFormat.format(sfdcMeetingDateTime) + "</h2><h3>System Current Date/Time:"
                        + dateFormat.format(SystemCurrentDateTime)
                        + "<br>*Meeting will open 15 minutes before scheduled time</h3><a href=" + logoutUrl
                        + ">Back</a>" + "  </center> ";
                return new ModelAndView("wait", "wait", wait);
            }
            //for Past Date
            if (SystemCurrentDateTime.compareTo(sfdcMeetingDateTime) == 1) {
                String wait = "<center> <h1>Meeting is Over!</h1><br></center>\n"
                        //                             +"<img src=\"${pageContext.request.contextPath}/images/bbbtime.jpg\" style=\"width:304px;height:228px\"/> "
                        + "  <center>  <h2>Meeting can not open.<br>\n"
                        + "        Meeting was scheduled on - \n<br>" + "<br>Meeting Date/Time:"
                        + dateFormat.format(sfdcMeetingDateTime) + "</h2><h3><br>System Current Date/Time:"
                        + dateFormat.format(SystemCurrentDateTime) + "<br><a href=" + logoutUrl + ">Back</a>"
                        + "  </h3>  </center> ";
                return new ModelAndView("wait", "wait", wait);

            }
            //                
        }

    } catch (Exception ex) {
        System.out.println("Exception=" + ex);
    }

    return null;
}

From source file:com.wisemapping.security.AuthenticationProvider.java

@Override()
public Authentication authenticate(@NotNull final Authentication auth) throws AuthenticationException {

    // All your user authentication needs
    final String email = auth.getName();

    final UserDetails userDetails = getUserDetailsService().loadUserByUsername(email);
    final User user = userDetails.getUser();
    final String credentials = (String) auth.getCredentials();
    if (user == null || credentials == null
            || !encoder.isPasswordValid(user.getPassword(), credentials, null)) {
        throw new BadCredentialsException("Username/Password does not match for " + auth.getPrincipal());
    }/*from   w ww  .  j ava 2  s  .  c  o  m*/
    userDetailsService.getUserService().auditLogin(user);
    return new UsernamePasswordAuthenticationToken(userDetails, credentials, userDetails.getAuthorities());
}

From source file:com.eazytec.webapp.filter.CustomAuthenticationProvider.java

License:asdf

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = String.valueOf(authentication.getPrincipal()).toLowerCase();
    String password = String.valueOf(authentication.getCredentials());
    logger.debug("Checking authentication for user {}" + username);
    logger.debug("userResponse: {}" + captchaCaptureFilter.getCaptcha_response());
    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
        throw new BadCredentialsException("No Username and/or Password Provided.");
    }/*from w w  w  .j  ava  2s  . co m*/

    licensePreCheck();

    Boolean isCaptchaNeeded = Boolean
            .valueOf(PropertyReader.getInstance().getPropertyFromFile("Boolean", "system.captcha.needed"));

    Boolean adEnabled = Boolean
            .valueOf(PropertyReader.getInstance().getPropertyFromFile("Boolean", "system.ad.enabled"));

    // if(!adEnabled){

    if (isCaptchaNeeded && StringUtils.isBlank(captchaCaptureFilter.getCaptcha_response())) {
        throw new BadCredentialsException("Captcha Response is Empty");
    }

    if (isCaptchaNeeded) {
        // else {
        // Send HTTP request to validate user's Captcha
        boolean captchaPassed = SimpleImageCaptchaServlet.validateCaptcha(
                captchaCaptureFilter.getCaptcha_challenge(), captchaCaptureFilter.getCaptcha_response());

        // Check if valid
        if (captchaPassed) {
            logger.debug("Captcha is valid!");
            resetCaptchaFields();
        } else {
            logger.debug("Captcha is invalid!");
            resetCaptchaFields();

            throw new BPMAccountStatusException(I18nUtil.getMessageProperty("errors.captcha.mismatch"));
        }
    }
    User user = null;
    if (!adEnabled) {
        user = userService.getUserById(username);
    }
    if (user == null && adEnabled) {
        throw new BadCredentialsException(I18nUtil.getMessageProperty("errors.password.mismatch"));
    }
    if (user == null || !user.isEnabled() && !adEnabled) {
        throw new BPMAccountStatusException(I18nUtil.getMessageProperty("errors.password.mismatch"));
    }
    if (passwordEncoder.isPasswordValid(user.getPassword(), password, saltSource.getSalt(user))) {
        Set<GrantedAuthority> authorityList = (Set<GrantedAuthority>) user.getAuthorities();
        return new UsernamePasswordAuthenticationToken(user, password, authorityList);
    } else {
        if (adEnabled) {
            throw new BadCredentialsException(I18nUtil.getMessageProperty("errors.password.mismatch"));
        } else {
            throw new BPMAccountStatusException(I18nUtil.getMessageProperty("errors.password.mismatch"));
        }
    }
}

From source file:org.apereo.services.persondir.support.SAMLCredentialPersonAttributeDao.java

/**
 * Per AbstractQueryPersonAttributeDao, this method returns "unmapped
 * attributes" which are transformed using the resultAttributeMapping
 * collection.  Use Attribute.name (rather than Attribute.friendlyName) in
 * these mapping definitions./*www  .ja  v  a 2 s  .co m*/
 */
@Override
protected List<IPersonAttributes> getPeopleForQuery(QueryBuilder queryBuilder, String queryUserName) {

    final String currentUserName = currentUserProvider.getCurrentUserName();
    ;
    if (currentUserName == null) {
        this.logger.warn("A null name was returned by the currentUserProvider, returning null.");
        return Collections.emptyList();
    }

    if (currentUserName.equals(queryUserName)) {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Adding attributes from the SAMLCredential for user " + currentUserName);
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            SAMLCredential credential = (SAMLCredential) authentication.getCredentials();

            if (credential != null) {

                // Provide some optional, TRACE-level logging for what we found
                if (logger.isTraceEnabled()) {
                    StringBuilder msg = new StringBuilder();
                    msg.append("Credential obtained!");
                    for (Attribute a : credential.getAttributes()) {
                        msg.append("\n    a.getName()=").append(a.getName())
                                .append("\n    a.getFriendlyName()=").append(a.getFriendlyName());
                        for (XMLObject xmlo : a.getAttributeValues()) {
                            String str = extractStringValue(xmlo);
                            msg.append("\n        value=" + str);
                        }
                    }
                    logger.trace(msg.toString());
                }

                // Marshall what we found into an (unmapped) IPersonAttributes object
                final Map<String, List<Object>> attributes = new HashMap<>();
                for (Attribute a : credential.getAttributes()) {
                    List<Object> list = new ArrayList<Object>();
                    for (XMLObject xmlo : a.getAttributeValues()) {
                        String str = extractStringValue(xmlo);
                        if (str != null) {
                            list.add(str);
                        }
                    }
                    attributes.put(a.getName(), list);
                }
                final IPersonAttributes personAttributes = new CaseInsensitiveNamedPersonImpl(currentUserName,
                        attributes);
                return Collections.singletonList(personAttributes);
            }

        }
    } else {
        // Optionally log the fact that we _didn't_ add attributes
        if (logger.isTraceEnabled()) {
            logger.trace(
                    "Skipping this DAO because " + "!currentUserName.equals(queryUserName);  currentUserName="
                            + currentUserName + ", queryUserName=" + queryUserName);
        }
    }

    return Collections.emptyList();

}