Example usage for org.springframework.security.authentication AuthenticationCredentialsNotFoundException AuthenticationCredentialsNotFoundException

List of usage examples for org.springframework.security.authentication AuthenticationCredentialsNotFoundException AuthenticationCredentialsNotFoundException

Introduction

In this page you can find the example usage for org.springframework.security.authentication AuthenticationCredentialsNotFoundException AuthenticationCredentialsNotFoundException.

Prototype

public AuthenticationCredentialsNotFoundException(String msg) 

Source Link

Document

Constructs an AuthenticationCredentialsNotFoundException with the specified message.

Usage

From source file:com.evolveum.midpoint.model.impl.security.AuthenticationEvaluatorImpl.java

private void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal,
        ProtectedStringType protectedString, MetadataType passwordMetadata,
        CredentialPolicyType passwordCredentialsPolicy) {
    if (protectedString == null) {
        recordAuthenticationFailure(principal, connEnv, "no stored password value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad");
    }/*ww w .jav a2  s  .  co  m*/
    if (passwordCredentialsPolicy == null) {
        return;
    }
    Duration maxAge = passwordCredentialsPolicy.getMaxAge();
    if (maxAge != null) {
        XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(passwordMetadata);
        if (changeTimestamp != null) {
            XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge);
            if (clock.isPast(passwordValidUntil)) {
                recordAuthenticationFailure(principal, connEnv, "password expired");
                throw new CredentialsExpiredException("web.security.provider.credential.expired");
            }
        }
    }
}

From source file:org.apache.syncope.core.spring.security.AuthDataAccessor.java

public JWTSSOProvider getJWTSSOProvider(final String issuer) {
    synchronized (this) {
        if (jwtSSOProviders == null) {
            jwtSSOProviders = new HashMap<>();

            implementationLookup.getJWTSSOProviderClasses().stream()
                    .map(clazz -> (JWTSSOProvider) ApplicationContextProvider.getBeanFactory().createBean(clazz,
                            AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true))
                    .forEachOrdered(jwtSSOProvider -> {
                        jwtSSOProviders.put(jwtSSOProvider.getIssuer(), jwtSSOProvider);
                    });//  w w w  .ja v a2  s  . c  o  m
        }
    }

    if (issuer == null) {
        throw new AuthenticationCredentialsNotFoundException("A null issuer is not permitted");
    }
    JWTSSOProvider provider = jwtSSOProviders.get(issuer);
    if (provider == null) {
        throw new AuthenticationCredentialsNotFoundException(
                "Could not find any registered JWTSSOProvider for issuer " + issuer);
    }

    return provider;
}

From source file:org.apache.syncope.core.spring.security.AuthDataAccessor.java

@Transactional
public Pair<String, Set<SyncopeGrantedAuthority>> authenticate(final JWTAuthentication authentication) {
    String username;//from   ww w. ja v a2s . co m
    Set<SyncopeGrantedAuthority> authorities;

    if (adminUser.equals(authentication.getClaims().getSubject())) {
        AccessToken accessToken = accessTokenDAO.find(authentication.getClaims().getTokenId());
        if (accessToken == null) {
            throw new AuthenticationCredentialsNotFoundException(
                    "Could not find an Access Token for JWT " + authentication.getClaims().getTokenId());
        }

        username = adminUser;
        authorities = getAdminAuthorities();
    } else {
        JWTSSOProvider jwtSSOProvider = getJWTSSOProvider(authentication.getClaims().getIssuer());
        Pair<User, Set<SyncopeGrantedAuthority>> resolved = jwtSSOProvider.resolve(authentication.getClaims());
        if (resolved == null || resolved.getLeft() == null) {
            throw new AuthenticationCredentialsNotFoundException(
                    "Could not find User " + authentication.getClaims().getSubject() + " for JWT "
                            + authentication.getClaims().getTokenId());
        }

        User user = resolved.getLeft();
        username = user.getUsername();
        authorities = resolved.getRight() == null ? Collections.emptySet() : resolved.getRight();
        LOG.debug("JWT {} issued by {} resolved to User {} with authorities {}",
                authentication.getClaims().getTokenId(), authentication.getClaims().getIssuer(), username,
                authorities);

        if (BooleanUtils.isTrue(user.isSuspended())) {
            throw new DisabledException("User " + username + " is suspended");
        }

        Optional<? extends CPlainAttr> authStatuses = confDAO.find("authentication.statuses");
        if (authStatuses.isPresent() && !authStatuses.get().getValuesAsStrings().contains(user.getStatus())) {
            throw new DisabledException("User " + username + " not allowed to authenticate");
        }

        if (BooleanUtils.isTrue(user.isMustChangePassword())) {
            LOG.debug("User {} must change password, resetting authorities", username);
            authorities = Collections
                    .singleton(new SyncopeGrantedAuthority(StandardEntitlement.MUST_CHANGE_PASSWORD));
        }
    }

    return Pair.of(username, authorities);
}

From source file:org.cloudfoundry.identity.uaa.ldap.PasswordComparisonAuthenticator.java

public DirContextOperations localCompareAuthenticate(DirContextOperations user, String password) {
    boolean match = false;
    try {// ww w .  j a v  a 2 s  . c o  m
        Attributes attributes = user.getAttributes();
        Attribute attr = attributes.get(getPasswordAttributeName());
        if (attr.size() == 0) {
            throw new AuthenticationCredentialsNotFoundException(
                    "Missing " + getPasswordAttributeName() + " attribute.");
        }
        for (int i = 0; (attr != null) && (!match) && (i < attr.size()); i++) {
            Object valObject = attr.get(i);
            if (valObject != null && valObject instanceof byte[]) {
                if (passwordEncoder instanceof DynamicPasswordComparator) {
                    byte[] received = password.getBytes();
                    byte[] stored = (byte[]) valObject;
                    match = ((DynamicPasswordComparator) passwordEncoder).comparePasswords(received, stored);
                } else {
                    String encodedPassword = passwordEncoder.encodePassword(password, null);
                    byte[] passwordBytes = Utf8.encode(encodedPassword);
                    match = Arrays.equals(passwordBytes, (byte[]) valObject);
                }
            }
        }
    } catch (NamingException e) {
        throw new BadCredentialsException("Bad credentials", e);
    }
    if (!match)
        throw new BadCredentialsException("Bad credentials");
    return user;
}

From source file:org.craftercms.social.util.support.security.CrafterProfileFilter.java

/**
 *
 * @param chain//  w  w w  .j  a  va 2 s  . c  om
 * @param httpRequest
 * @param httpResponse
 * @param token
 * @param tenantName
 * @param cipher
 * @throws IOException
 * @throws ServletException
 * @throws org.craftercms.social.exceptions.AuthenticationException
 */
private void authenticateWithSimpleToken(FilterChain chain, HttpServletRequest httpRequest,
        HttpServletResponse httpResponse, String token, String tenantName, SimpleDesCipher cipher)
        throws IOException, ServletException, org.craftercms.social.exceptions.AuthenticationException {

    if (token != null && !token.isEmpty()) {
        if (profile.validateUserToken(token)) {

            final Profile userProfile = profile.getUserInformation(token);

            // validate tenant, exception thrown for failure
            validateTenant(httpRequest.getServerName(), tenantName, userProfile.getTenantName(),
                    userProfile.getId());

            SecurityContextHolder.getContext().setAuthentication(getCrafterAuthToken(userProfile));

            // generate the encrypted token and set in response
            httpResponse.addCookie(getCipherCookie(cipher, token, userProfile));

            chain.doFilter(httpRequest, httpResponse);

        } else {
            profile.resetAppToken();
            failRequest(httpRequest, httpResponse, new BadCredentialsException("Token is no longer valid"));
        }

    } else if (token.isEmpty()) { // ANONYMOUS support
        SecurityContextHolder.getContext().setAuthentication(getCrafterAuthAnonymousToken());
        chain.doFilter(httpRequest, httpResponse);
    } else {

        failRequest(httpRequest, httpResponse,
                new AuthenticationCredentialsNotFoundException("Need param is not on the request"));
    }
}

From source file:org.jamwiki.authentication.WikiUserDetails.java

/**
 * Utility method for converting a Spring Security <code>Authentication</code>
 * object into a <code>WikiUserDetails</code>.  If the user is logged-in then the
 * <code>Authentication</code> object will have the <code>WikiUserDetails</code>
 * as its principal.  If the user is not logged in then create an empty
 * <code>WikiUserDetails</code> object and assign it the same authorities as the
 * <code>Authentication</code> object.
 *
 * @param auth The Spring Security <code>Authentication</code> object that is being
 *  converted into a <code>WikiUserDetails</code> object.
 * @return Returns a <code>WikiUserDetails</code> object that corresponds to the
 *  Spring Security <code>Authentication</code> object.  If the user is not currently
 *  logged-in then an empty <code>WikiUserDetails</code> with the same authorities
 *  as the <code>Authentication</code> object is returned.  This method
 *  will never return <code>null</code>.
 * @throws AuthenticationCredentialsNotFoundException If authentication
 *  credentials are unavailable.//  ww  w .j a v a2  s.  com
 */
public static WikiUserDetails initWikiUserDetails(Authentication auth)
        throws AuthenticationCredentialsNotFoundException {
    if (auth == null) {
        throw new AuthenticationCredentialsNotFoundException("No authentication credential available");
    }
    if (auth instanceof AnonymousAuthenticationToken || !(auth.getPrincipal() instanceof UserDetails)) {
        // anonymous user
        return new WikiUserDetails(ANONYMOUS_USER_USERNAME, "", true, true, true, true, auth.getAuthorities());
    }
    // logged-in (or remembered) user
    if (auth.getPrincipal() instanceof WikiUserDetails) {
        return (WikiUserDetails) auth.getPrincipal();
    }
    return new WikiUserDetails((UserDetails) auth.getPrincipal());
}

From source file:org.jamwiki.servlets.ServletUtil.java

/**
 * Retrieve the current <code>WikiUser</code> using the
 * <code>WikiUserDetails</code> from Spring Security
 * <code>SecurityContextHolder</code>. If there is no current user (the user
 * is not logged in) then this method will return an empty WikiUser. The
 * method will never return <code>null</code>.
 * //from   ww w  .ja  va 2s.  co m
 * @return The current logged-in <code>WikiUser</code>, or an empty WikiUser
 *         if there is no user currently logged in.
 */
public static WikiUser currentWikiUser() throws AuthenticationCredentialsNotFoundException {
    WikiUserDetails userDetails = ServletUtil.currentUserDetails();
    WikiUser user = new WikiUser();
    String username = userDetails.getUsername();
    if (username.equals(WikiUserDetails.ANONYMOUS_USER_USERNAME)) {
        return user;
    }
    if (!WikiUtil.isFirstUse() && !WikiUtil.isUpgrade()) {
        try {
            // FIXME - do not lookup the user every time this method is called, that
            // will kill performance
            user = WikiBase.getDataHandler().lookupWikiUser(username);
        } catch (DataAccessException e) {
            logger.severe("Failure while retrieving user from database with login: " + username, e);
            return user;
        }
        if (user == null) {
            // invalid user. someone has either spoofed a cookie or the user account
            // is no longer in
            // the database.
            logger.warning(
                    "No user exists for principal found in security context authentication: " + username);
            SecurityContextHolder.clearContext();
            throw new AuthenticationCredentialsNotFoundException("Invalid user credentials found - username "
                    + username + " does not exist in this wiki installation");
        }
    }
    return user;
}