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:org.jasypt.spring.security3.TokenBasedRememberMeServices.java

public void onLoginSuccess(final HttpServletRequest request, final HttpServletResponse response,
        final Authentication successfulAuthentication) {

    if (this.digester == null) {
        throw new IllegalStateException("Service incorrectly initialized: a "
                + "digester has not been set. A value must be specified for the \"digester\""
                + " property in service of class " + this.getClass().getName());
    }/* ww  w. ja v  a 2s  . co m*/

    String username = null;
    String password = null;

    if (successfulAuthentication.getPrincipal() instanceof UserDetails) {
        final UserDetails userDetails = (UserDetails) successfulAuthentication.getPrincipal();
        username = userDetails.getUsername();
        password = userDetails.getPassword();
    } else {
        username = successfulAuthentication.getPrincipal().toString();
        password = (successfulAuthentication.getCredentials() == null ? null
                : successfulAuthentication.getCredentials().toString());
    }

    if (CommonUtils.isEmpty(username) || CommonUtils.isEmpty(password)) {
        // both user name and password have to be non-empty. No cookie to be added
        return;
    }

    final int tokenValiditySeconds = getTokenValiditySeconds();
    final long expiryTime = System.currentTimeMillis()
            + 1000L * (tokenValiditySeconds < 0 ? TWO_WEEKS_S : tokenValiditySeconds);

    final String signature = this.digester.digest(getSignatureData(expiryTime, username, password));

    setCookie(new String[] { username, Long.toString(expiryTime), signature }, tokenValiditySeconds, request,
            response);

    if (this.logger.isDebugEnabled()) {
        this.logger.debug(
                "Added remember-me cookie for user '" + username + "', expiry: '" + new Date(expiryTime) + "'");
    }

}

From source file:org.dspace.EDMExport.service.EDMExportAuthenticationManager.java

/**
 * Redefinimos el mtodo para autenticarse
 * //from w w w  .j a  v a2s.c  o  m
 * @param auth objeto de Spring de Authentication {@link Authentication}
 * @return UsernamePasswordAuthenticationToken {@link Authentication}
 * @throws AuthenticationException
 */
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    logger.debug("Performing EDMExport authentication");

    try {
        // Buscar usuario con login y grupo o slo con login
        if (groupIDStr != null && !groupIDStr.isEmpty()) {
            eperson = daoEperson.getEperson(auth.getName(), Integer.parseInt(groupIDStr));
        } else
            eperson = daoEperson.getEperson(auth.getName());
    } catch (Exception e) {
        logger.error("User " + auth.getName() + " does not exists! " + e.getMessage() + "," + e.toString(), e);
        //SecurityContextHolder.getContext().setAuthentication(null);
        throw new BadCredentialsException("User does not exists!");
    }

    // Validamos el password
    if (!passwordEncoder.isPasswordValid(eperson.getPassword(), (String) auth.getCredentials(), null)) {
        logger.error("Wrong password!" + eperson.getPassword() + " " + (String) auth.getCredentials());
        throw new BadCredentialsException("Wrong password!");
    }

    // Comprobamos que el login no se igual que el password, poco seguridad
    if (auth.getName().equals(auth.getCredentials())) {
        logger.debug("Entered username and password are the same!");
        throw new BadCredentialsException("Entered username and password are the same!");
    } else {
        logger.debug("User details are good and ready to go");
        return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(),
                getAuthorities(eperson.getAccess()));
    }
}

From source file:org.ligoj.app.http.security.RestAuthenticationProvider.java

/**
 * Return a new authentication with the the real use name.
 *//*from   w ww  .j a va2s.c o  m*/
private Authentication newAuthentication(final String userName, final String userpassword,
        final Authentication authentication, final HttpResponse httpResponse) {
    final List<String> cookies = Arrays.stream(httpResponse.getAllHeaders())
            .filter(header -> "set-cookie".equals(header.getName())).map(Header::getValue)
            .collect(Collectors.toList());

    // Get the optional real user name if provided
    final String realUserName = Optional.ofNullable(httpResponse.getFirstHeader("X-Real-User"))
            .map(Header::getValue).orElse(userName);
    if (realUserName.equals(userName)) {
        log.info("Success authentication of {}[{}]", realUserName, userpassword.length(), realUserName);
    } else {
        log.info("Success authentication of {}[{}] using login {}", realUserName, userpassword.length(),
                userName);
    }

    // Return the authentication token
    return new CookieUsernamePasswordAuthenticationToken(realUserName, authentication.getCredentials(),
            authentication.getAuthorities(), cookies);

}

From source file:org.geonode.security.GeoNodeCookieProcessingFilter.java

/**
 * /*from   w w w. ja v a  2s. c  o m*/
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest httpRequest = (HttpServletRequest) request;

    final SecurityContext securityContext = SecurityContextHolder.getContext();
    final Authentication existingAuth = securityContext.getAuthentication();

    final String gnCookie = getGeoNodeCookieValue(httpRequest);

    final boolean alreadyAuthenticated = existingAuth != null && existingAuth.isAuthenticated();
    final boolean anonymous = existingAuth == null || existingAuth instanceof AnonymousAuthenticationToken;
    // if logging in via geoserver web form, we want to short circuit the cookie
    // check below which might get triggered with an anon geonode cookie
    // the result looks like the login worked but because we replace the
    // auth below, it functionaly fails
    final boolean loggedInWithPassword = existingAuth instanceof UsernamePasswordAuthenticationToken
            && alreadyAuthenticated;
    final boolean hasPreviouslyValidatedGeoNodeCookie = (existingAuth instanceof GeoNodeSessionAuthToken)
            && existingAuth.getCredentials().equals(gnCookie);

    if (hasPreviouslyValidatedGeoNodeCookie)
        existingAuth.setAuthenticated(true);

    // if we still need to authenticate and we find the cookie, consult GeoNode for
    // an authentication
    final boolean authenticationRequired = (!alreadyAuthenticated || anonymous
            || !hasPreviouslyValidatedGeoNodeCookie);

    if (!loggedInWithPassword && authenticationRequired && gnCookie != null) {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine(
                    "Found GeoNode cookie - checking if we have the authorizations in cache or if we have to reload from GeoNode");
        }
        try {
            Object principal = existingAuth == null ? null : existingAuth.getPrincipal();
            Collection<? extends GrantedAuthority> authorities = existingAuth == null ? null
                    : existingAuth.getAuthorities();
            Authentication authRequest = new GeoNodeSessionAuthToken(principal, gnCookie, authorities);
            final Authentication authResult = getSecurityManager().authenticate(authRequest);
            LOGGER.log(Level.FINE, "authResult : {0}", authResult);
            securityContext.setAuthentication(authResult);
        } catch (AuthenticationException e) {
            // we just go ahead and fall back on basic authentication
            LOGGER.log(Level.WARNING, "Error connecting to the GeoNode server for authentication purposes", e);
        }
    }

    // move forward along the chain
    chain.doFilter(request, response);
}

From source file:cz.muni.fi.editor.services.commons.impl.SecurityServiceImpl.java

@Override
@Transactional(readOnly = true)//from ww  w.j  a  v  a  2  s.  com
public void refresh(Long userID) {
    if (SecurityContextHolder.getContext().getAuthentication() != null
            && SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null) {
        Authentication current = SecurityContextHolder.getContext().getAuthentication();
        UserDTO principal = (UserDTO) current.getPrincipal();
        if (principal.getId().equals(userID)) {
            User dao = new User();
            dao.setId(principal.getId());

            List<OrganizationDTO> member = organizationDAO.getOrganizationForUser(dao, true).stream().map(o -> {
                OrganizationDTO dto = new OrganizationDTO();
                dto.setId(o.getId());
                return dto;
            }).collect(Collectors.toList());

            List<OrganizationDTO> owner = organizationDAO.ownedBy(dao).stream().map(o -> {
                OrganizationDTO dto = new OrganizationDTO();
                dto.setId(o.getId());
                return dto;
            }).collect(Collectors.toList());

            principal.init(owner, member);

            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
                    principal, current.getCredentials(), principal.getAuthorities()));
        }
    }
}

From source file:com.launchkey.example.springmvc.LaunchKeyAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();

    try {//from  ww  w. j  av a  2  s.  c  om
        this.authManager.login(username);
        Boolean authorized = null;
        while (authorized == null) {
            Thread.sleep(100L);
            authorized = this.authManager.isAuthorized();
        }
        if (authorized == null) {
            throw new InsufficientAuthenticationException(
                    "The authentication request was not responded to in sufficient time");
        } else if (!authorized) {
            throw new InsufficientAuthenticationException("The authentication request was denied");
        }
    } catch (InterruptedException e) {
        throw new AuthenticationServiceException("Sleep error");
    } catch (AuthManager.AuthException e) {
        if (e.getCause() instanceof LaunchKeyException) {
            throw new BadCredentialsException("Authentication failure", e.getCause());
        }
    }

    return new UsernamePasswordAuthenticationToken(username, authentication.getCredentials(),
            new ArrayList<GrantedAuthority>());
}

From source file:com.capinfo.common.security.authentication.dao.SecurityDaoAuthenticationProvider.java

/**
 * ?org.springframework.security.authentication.dao.
 * AbstractUserDetailsAuthenticationProvider.authenticate
 * //w  ww  .  j  av a  2  s  .c om
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

    // Determine username  credentials
    String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();

    boolean cacheWasUsed = true;
    UserDetails user = getUserCache().getUserFromCache(username);
    // Ehcache?UserDetailspasswordnull.usernamepassword?
    // boolean userOutCache=user == null;
    boolean userOutCache = user == null || StringUtils.isBlank(user.getUsername())
            || StringUtils.isBlank(user.getPassword());
    if (userOutCache) {
        cacheWasUsed = false;

        try {
            user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);

            if (!authentication.getCredentials().toString().equals(user.getPassword())) {
                throw new BadCredentialsException(messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }
        } catch (UsernameNotFoundException notFound) {
            logger.debug("User '" + username + "' not found");

            if (hideUserNotFoundExceptions) {
                throw new BadCredentialsException(messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            } else {
                throw notFound;
            }
        }

        Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
    }

    try {
        getPreAuthenticationChecks().check(user);
    } catch (AuthenticationException exception) {
        if (cacheWasUsed) {
            // There was a problem, so try again after checking
            // we're using latest data (i.e. not from the cache)
            cacheWasUsed = false;
            user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
            getPreAuthenticationChecks().check(user);
        } else {
            throw exception;
        }
    }

    getPostAuthenticationChecks().check(user);

    if (!cacheWasUsed) {
        getUserCache().putUserInCache(user);
        UserDetails user2 = getUserCache().getUserFromCache(username);
    }

    Object principalToReturn = user;

    if (isForcePrincipalAsString()) {
        principalToReturn = user.getUsername();
    }

    return createSuccessAuthentication(principalToReturn, authentication, user);
}

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  w w .  java 2 s.c om*/
        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:business.security.CustomAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication == null || authentication.getName() == null) {
        log.error("Empty authentication.");
        return null;
    }//  w  w  w. j av a2 s. c  o m
    String username = authentication.getName().toLowerCase();
    log.info("username: " + username);
    User user = userRepository.findByUsernameAndActiveTrueAndEmailValidatedTrueAndDeletedFalse(username);
    if (user != null) {
        if (user.isAccountTemporarilyBlocked()) {
            Date now = new Date();
            long interval = now.getTime() - user.getAccountBlockStartTime().getTime();
            if (interval > ACCOUNT_BLOCKING_PERIOD * 1000) {
                // unblock account
                log.info("Unblocking blocked account for user " + user.getUsername());
                user.resetFailedLoginAttempts();
                user.setAccountTemporarilyBlocked(false);
                user = userRepository.save(user);
            } else {
                // account is temporarily blocked, deny access.
                log.info("Account still blocked for user " + user.getUsername() + ". Access denied.");
                throw new UserAccountBlocked();
            }
        }
        if (passwordService.getEncoder().matches(authentication.getCredentials().toString(),
                user.getPassword())) {
            log.info("AuthenticationProvider: OK");
            if (user.getFailedLoginAttempts() > 0) {
                user.resetFailedLoginAttempts();
                user = userRepository.save(user);
            }
            UserAuthenticationToken token = new UserAuthenticationToken(user, getAuthorityList(user));
            log.info("Token: " + token);
            return token;
        }
        // failed login attempt
        user.incrementFailedLoginAttempts();
        log.info("Login failed for user " + user.getUsername() + ". Failed attempt number "
                + user.getFailedLoginAttempts() + ".");
        if (user.getFailedLoginAttempts() >= MAX_FAILED_LOGIN_ATTEMPTS) {
            // block account
            user.setAccountTemporarilyBlocked(true);
            user.setAccountBlockStartTime(new Date());
            userRepository.save(user);
            throw new UserAccountBlocked();
        }
        userRepository.save(user);
    }
    return null;
}

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 ww . j  a  va 2s . c om*/
    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;
}