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.javaforge.tapestry.acegi.service.impl.SecurityUtilsImpl.java

public void checkSecurity(Object object, Collection<ConfigAttribute> attr) {
    Assert.notNull(object, "Object was null");

    if (attr != null) {
        if (getLog().isDebugEnabled()) {
            getLog().debug("Secure object: " + object.toString() + "; ConfigAttributes: " + attr.toString());
        }/*from  w w  w  .j  a  v a  2s. co m*/

        // We check for just the property we're interested in (we do
        // not call Context.validate() like the ContextInterceptor)
        if (SecurityContextHolder.getContext().getAuthentication() == null) {
            throw new AuthenticationCredentialsNotFoundException(
                    messages.getMessage("AbstractSecurityInterceptor.authenticationNotFound",
                            "An Authentication object was not found in the SecurityContext"));
        }

        // Attempt authentication if not already authenticated, or user always wants reauthentication
        Authentication authenticated;

        SecurityContext ctx = SecurityContextHolder.getContext();

        if (ctx.getAuthentication() == null || !ctx.getAuthentication().isAuthenticated()
                || alwaysReauthenticate) {
            authenticated = this.authenticationManager
                    .authenticate(SecurityContextHolder.getContext().getAuthentication());

            // We don't authenticated.setAuthentication(true), because each provider should do that
            if (getLog().isDebugEnabled()) {
                getLog().debug("Successfully Authenticated: " + authenticated.toString());
            }

            SecurityContextHolder.getContext().setAuthentication(authenticated);
        } else {
            authenticated = SecurityContextHolder.getContext().getAuthentication();

            if (getLog().isDebugEnabled()) {
                getLog().debug("Previously Authenticated: " + authenticated.toString());
            }
        }

        // Attempt authorization
        this.accessDecisionManager.decide(authenticated, object, attr);

        if (getLog().isDebugEnabled()) {
            getLog().debug("Authorization successful");
        }

        // Attempt to run as a different user
        Authentication runAs = this.runAsManager.buildRunAs(authenticated, object, attr);

        if (runAs == null) {
            if (getLog().isDebugEnabled()) {
                getLog().debug("RunAsManager did not change Authentication object");
            }
        } else {
            if (getLog().isDebugEnabled()) {
                getLog().debug("Switching to RunAs Authentication: " + runAs.toString());
            }
            SecurityContextHolder.getContext().setAuthentication(runAs);
        }
    } else {
        if (getLog().isDebugEnabled()) {
            getLog().debug("Public object - authentication not attempted");
        }
    }
}

From source file:org.keycloak.adapters.springsecurity.authentication.DirectAccessGrantAuthenticationProvider.java

/**
 * Returns the username for the given principal.
 *
 * @param principal the principal to authenticate
 * @return the username from the given <code>principal</code>
 * @throws AuthenticationCredentialsNotFoundException if the username cannot be resolved
 *///from   w  w w.j  av a  2 s . co m
protected String resolveUsername(Object principal) {

    if (principal instanceof String)
        return (String) principal;

    if (principal instanceof UserDetails)
        return ((UserDetails) principal).getUsername();

    throw new AuthenticationCredentialsNotFoundException("Can't find username on: " + principal);
}

From source file:org.opendatakit.security.spring.UserDetailsServiceImpl.java

@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException, DataAccessException {
    if (name == null) {
        throw new IllegalStateException("Username cannot be null");
    }//w  w  w . j av a 2  s . c om

    User user = userService.getDaemonAccountUser();

    final String uriUser;
    final String password;
    final String salt;
    final Set<GrantedAuthority> grantedAuthorities;
    final boolean isEnabled = true;
    final boolean isCredentialNonExpired = true;
    try {
        if (credentialType == CredentialType.Username) {
            RegisteredUsersTable registeredUsersTable;
            // first call from digest, basic or forms-based auth
            if (name.startsWith(RegisteredUsersTable.UID_PREFIX)) {
                registeredUsersTable = RegisteredUsersTable.getUserByUri(name, datastore, user);
                if (registeredUsersTable == null) {
                    throw new UsernameNotFoundException("UID " + name + " is not recognized.");
                }
            } else {
                registeredUsersTable = RegisteredUsersTable.getUniqueUserByUsername(name, datastore, user);
                if (registeredUsersTable == null) {
                    throw new UsernameNotFoundException(
                            "User " + name + " is not registered or the registered users table is corrupt.");
                }
            }
            uriUser = registeredUsersTable.getUri();

            // Along with BasicUsingDigest* classes, we allow both types of authentication to use the
            // same DB field for password.
            switch (passwordType) {
            case BasicAuth:
                // password = registeredUsersTable.getBasicAuthPassword();
                // salt = registeredUsersTable.getBasicAuthSalt();
                // break;
            case DigestAuth:
                password = registeredUsersTable.getDigestAuthPassword();
                salt = UUID.randomUUID().toString();
                break;
            default:
                throw new AuthenticationCredentialsNotFoundException(
                        "Password type " + passwordType.toString() + " cannot be interpretted");
            }

            grantedAuthorities = getGrantedAuthorities(registeredUsersTable.getUri());
            if (password == null) {
                throw new AuthenticationCredentialsNotFoundException("User " + name
                        + " does not have a password configured. You must close and re-open your browser to clear this error.");
            }
        } else {
            // OAuth2 token...
            // there is no password for an OAuth2 credential
            if (passwordType != PasswordType.Random) {
                throw new AuthenticationCredentialsNotFoundException(
                        "Password type " + passwordType.toString() + " cannot be interpretted");
            }
            // set password and salt to unguessable strings...
            password = UUID.randomUUID().toString();
            salt = UUID.randomUUID().toString();

            // try to find user in registered users table...
            RegisteredUsersTable eUser = RegisteredUsersTable.getUniqueUserByEmail(name, datastore, user);
            if (eUser != null) {
                uriUser = eUser.getUri();
                grantedAuthorities = getGrantedAuthorities(eUser.getUri());
            } else {
                throw new UsernameNotFoundException("User " + name + " is not registered");
            }
        }
    } catch (ODKDatastoreException e) {
        throw new TransientDataAccessResourceException("persistence layer problem", e);
    }

    return new OdkServerUser(uriUser, password, salt, "-undefined-", isEnabled, true, isCredentialNonExpired,
            true, grantedAuthorities);
}

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

private boolean checkCredentials(MidPointPrincipal principal, T authnCtx, ConnectionEnvironment connEnv) {

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    if (credentials == null || getCredential(credentials) == null) {
        recordAuthenticationFailure(principal, connEnv, "no credentials in user");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid");
    }//  w  ww  .j av a  2s  .  c o  m

    CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);

    // Lockout
    if (isLockedOut(getCredential(credentials), credentialsPolicy)) {
        recordAuthenticationFailure(principal, connEnv, "password locked-out");
        throw new LockedException("web.security.provider.locked");
    }

    if (suportsAuthzCheck()) {
        // Authorizations
        if (!hasAnyAuthorization(principal)) {
            recordAuthenticationFailure(principal, connEnv, "no authorizations");
            throw new DisabledException("web.security.provider.access.denied");
        }
    }

    // Password age
    checkPasswordValidityAndAge(connEnv, principal, getCredential(credentials), credentialsPolicy);

    return passwordMatches(connEnv, principal, getCredential(credentials), authnCtx);
}

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

/**
 * Utility method for converting a Spring Security <code>Authentication</code>
 * object into a <code>WikiUserDetailsImpl</code>.  If the user is logged-in then the
 * <code>Authentication</code> object will have the <code>WikiUserDetailsImpl</code>
 * as its principal.  If the user is not logged in then create an empty
 * <code>WikiUserDetailsImpl</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>WikiUserDetailsImpl</code> object.
 * @return Returns a <code>WikiUserDetailsImpl</code> object that corresponds to the
 *  Spring Security <code>Authentication</code> object.  If the user is not currently
 *  logged-in then an empty <code>WikiUserDetailsImpl</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.// www  .java 2  s  .  com
 */
public static WikiUserDetailsImpl initWikiUserDetailsImpl(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 WikiUserDetailsImpl(ANONYMOUS_USER_USERNAME, "", true, true, true, true,
                auth.getAuthorities());
    }
    // logged-in (or remembered) user
    if (auth.getPrincipal() instanceof WikiUserDetailsImpl) {
        return (WikiUserDetailsImpl) auth.getPrincipal();
    }
    return new WikiUserDetailsImpl((UserDetails) auth.getPrincipal());
}

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

/**
 * Special-purpose method used for Web Service authentication based on javax.security callbacks.
 *
 * In that case there is no reasonable way how to reuse existing methods. Therefore this method is NOT part of the
 * AuthenticationEvaluator interface. It is mostly a glue to make the old Java security code work.
 *//*from   ww w .ja  v  a  2 s. c om*/
public String getAndCheckUserPassword(ConnectionEnvironment connEnv, String enteredUsername)
        throws AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
        CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException,
        UsernameNotFoundException {

    MidPointPrincipal principal = getAndCheckPrincipal(connEnv, enteredUsername, true);

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    if (credentials == null) {
        recordAuthenticationFailure(principal, connEnv, "no credentials in user");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid");
    }
    PasswordType passwordType = credentials.getPassword();
    SecurityPolicyType securityPolicy = principal.getApplicableSecurityPolicy();
    PasswordCredentialsPolicyType passwordCredentialsPolicy = SecurityUtil
            .getEffectivePasswordCredentialsPolicy(securityPolicy);

    // Lockout
    if (isLockedOut(passwordType, passwordCredentialsPolicy)) {
        recordAuthenticationFailure(principal, connEnv, "password locked-out");
        throw new LockedException("web.security.provider.locked");
    }

    // Authorizations
    if (!hasAnyAuthorization(principal)) {
        recordAuthenticationFailure(principal, connEnv, "no authorizations");
        throw new AccessDeniedException("web.security.provider.access.denied");
    }

    // Password age
    checkPasswordValidityAndAge(connEnv, principal, passwordType.getValue(), passwordType.getMetadata(),
            passwordCredentialsPolicy);

    return getPassword(connEnv, principal, passwordType.getValue());
}

From source file:org.mitre.oauth2.service.impl.DefaultOAuth2ProviderTokenService.java

@Override
public OAuth2AccessTokenEntity createAccessToken(OAuth2Authentication authentication)
        throws AuthenticationException, InvalidClientException {
    if (authentication != null && authentication.getOAuth2Request() != null) {
        // look up our client
        OAuth2Request clientAuth = authentication.getOAuth2Request();

        ClientDetailsEntity client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());

        if (client == null) {
            throw new InvalidClientException("Client not found: " + clientAuth.getClientId());
        }/* w  ww.  java2  s.c om*/

        OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();//accessTokenFactory.createNewAccessToken();

        // attach the client
        token.setClient(client);

        // inherit the scope from the auth, but make a new set so it is
        //not unmodifiable. Unmodifiables don't play nicely with Eclipselink, which
        //wants to use the clone operation.
        Set<SystemScope> scopes = scopeService.fromStrings(clientAuth.getScope());

        // remove any of the special system scopes
        scopes = scopeService.removeReservedScopes(scopes);

        token.setScope(scopeService.toStrings(scopes));

        // make it expire if necessary
        if (client.getAccessTokenValiditySeconds() != null && client.getAccessTokenValiditySeconds() > 0) {
            Date expiration = new Date(
                    System.currentTimeMillis() + (client.getAccessTokenValiditySeconds() * 1000L));
            token.setExpiration(expiration);
        }

        // attach the authorization so that we can look it up later
        AuthenticationHolderEntity authHolder = new AuthenticationHolderEntity();
        authHolder.setAuthentication(authentication);
        authHolder = authenticationHolderRepository.save(authHolder);

        token.setAuthenticationHolder(authHolder);

        // attach a refresh token, if this client is allowed to request them and the user gets the offline scope
        if (client.isAllowRefresh() && token.getScope().contains(SystemScopeService.OFFLINE_ACCESS)) {
            OAuth2RefreshTokenEntity savedRefreshToken = createRefreshToken(client, authHolder);

            token.setRefreshToken(savedRefreshToken);
        }

        OAuth2AccessTokenEntity enhancedToken = (OAuth2AccessTokenEntity) tokenEnhancer.enhance(token,
                authentication);

        OAuth2AccessTokenEntity savedToken = tokenRepository.saveAccessToken(enhancedToken);

        //Add approved site reference, if any
        OAuth2Request originalAuthRequest = authHolder.getAuthentication().getOAuth2Request();

        if (originalAuthRequest.getExtensions() != null
                && originalAuthRequest.getExtensions().containsKey("approved_site")) {

            Long apId = Long.parseLong((String) originalAuthRequest.getExtensions().get("approved_site"));
            ApprovedSite ap = approvedSiteService.getById(apId);
            Set<OAuth2AccessTokenEntity> apTokens = ap.getApprovedAccessTokens();
            apTokens.add(savedToken);
            ap.setApprovedAccessTokens(apTokens);
            approvedSiteService.save(ap);

        }

        if (savedToken.getRefreshToken() != null) {
            tokenRepository.saveRefreshToken(savedToken.getRefreshToken()); // make sure we save any changes that might have been enhanced
        }

        return savedToken;
    }

    throw new AuthenticationCredentialsNotFoundException("No authentication credentials found");
}

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

private <P extends CredentialPolicyType> void checkPasswordValidityAndAge(ConnectionEnvironment connEnv,
        @NotNull MidPointPrincipal principal, C credentials, P passwordCredentialsPolicy) {
    if (credentials == null) {
        recordAuthenticationFailure(principal, connEnv, "no stored credential value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.credential.bad");
    }// w ww  .  j  av a2 s . c  o m

    validateCredentialNotNull(connEnv, principal, credentials);

    if (passwordCredentialsPolicy == null) {
        return;
    }

    Duration maxAge = passwordCredentialsPolicy.getMaxAge();
    if (maxAge != null) {
        MetadataType credentialMetedata = credentials.getMetadata();
        XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(credentialMetedata);
        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:springacltutorial.infrastructure.MyMethodSecurityInterceptor.java

/**
 * Helper method which generates an exception containing the passed reason,
 * and publishes an event to the application context.
 * <p>//from www.ja  v  a  2 s  .c om
 * Always throws an exception.
 * 
 * @param reason
 *            to be provided in the exception detail
 * @param secureObject
 *            that was being called
 * @param configAttribs
 *            that were defined for the secureObject
 */
private void credentialsNotFound(String reason, Object secureObject,
        Collection<ConfigAttribute> configAttribs) {
    AuthenticationCredentialsNotFoundException exception = new AuthenticationCredentialsNotFoundException(
            reason);

    AuthenticationCredentialsNotFoundEvent event = new AuthenticationCredentialsNotFoundEvent(secureObject,
            configAttribs, exception);
    publishEvent(event);

    throw exception;
}