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

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

Introduction

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

Prototype

public InternalAuthenticationServiceException(String message, Throwable cause) 

Source Link

Usage

From source file:demo.security.MongoDBAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    UserDetails loadedUser;/*from  w w w . j ava  2s .c  o m*/

    try {
        Client client = users.findOne("{#: #}", Client.USERNAME, username).as(Client.class);
        loadedUser = new User(client.getUsername(), client.getPassword(), client.getRoles());
    } catch (Exception repositoryProblem) {
        throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
    }

    if (loadedUser == null) {
        throw new InternalAuthenticationServiceException(
                "UserDetailsService returned null, which is an interface contract violation");
    }
    return loadedUser;
}

From source file:com.rockagen.gnext.service.spring.security.extension.ExAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    UserDetails loadedUser;/*from  w  w  w . java  2 s. c o  m*/

    try {
        loadedUser = loadUser(username, authentication.getCredentials().toString());
    } catch (Exception repositoryProblem) {
        throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
    }

    return loadedUser;
}

From source file:org.juiser.spring.security.authentication.HeaderAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    HeaderAuthenticationToken token = (HeaderAuthenticationToken) authentication;

    Object creds = token.getCredentials();
    if (!(creds instanceof String)) {
        throw new BadCredentialsException("HeaderAuthenticationToken credentials must be a String.");
    }/*w  w  w.  j  ava  2 s. c om*/

    String value = (String) creds;
    if (!StringUtils.hasText(value)) {
        throw new BadCredentialsException(
                "HeaderAuthenticationToken credentials String cannot be null or empty.");
    }

    UserDetails details;
    try {
        details = converter.apply(value);
    } catch (JwtException e) {
        String msg = "Invalid or unsupported request header JWT: " + e.getMessage();
        throw new BadCredentialsException(msg, e);
    } catch (Exception e) {
        String msg = "Unexpected exception during authentication header parsing: " + e.getMessage();
        throw new InternalAuthenticationServiceException(msg, e);
    }

    return new ForwardedUserAuthentication(details);
}

From source file:cn.com.fubon.springboot.starter.jwt.auth.JwtTokenServiceImpl.java

@Override
public Authentication parseJwtToken(String jwtToken) throws AuthenticationException {
    try {//from   w ww.  j  a  v  a2 s.  co m
        Claims claims = Jwts.parser().setSigningKey(secretkey).parseClaimsJws(jwtToken).getBody();

        return JwtAuthenticationToken.of(claims);
    } catch (ExpiredJwtException | SignatureException e) {
        throw new BadCredentialsException(e.getMessage(), e);
    } catch (UnsupportedJwtException | MalformedJwtException e) {
        throw new AuthenticationServiceException(e.getMessage(), e);
    } catch (IllegalArgumentException e) {
        throw new InternalAuthenticationServiceException(e.getMessage(), e);
    }
}

From source file:io.gravitee.management.idp.repository.authentication.RepositoryAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    try {/*  ww w .  j  av a  2 s.  c o  m*/
        UserEntity user = userService.findByName(username);
        return mapUserEntityToUserDetails(user);
    } catch (UserNotFoundException notFound) {
        throw new UsernameNotFoundException("User '" + username + "' not found", notFound);
    } catch (Exception repositoryProblem) {
        LOGGER.error("Failed to retrieveUser : {}", username, repositoryProblem);
        throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
    }
}

From source file:com.hp.autonomy.frontend.configuration.authentication.CommunityAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final com.hp.autonomy.frontend.configuration.authentication.Authentication<?> authenticationConfig = configService
            .getConfig().getAuthentication();
    final String authenticationMethod = authenticationConfig.getMethod();

    if (!(authenticationConfig instanceof CommunityAuthentication)
            || LoginTypes.DEFAULT.equals(authenticationMethod)) {
        return null;
    }/*from ww w .j  ava2 s  .  c  o  m*/

    final String username = authentication.getName();
    final String password = authentication.getCredentials().toString();

    try {
        final boolean isAuthenticated = userService.authenticateUser(username, password, authenticationMethod);

        if (!isAuthenticated) {
            throw new BadCredentialsException("Bad credentials");
        }

        final UserRoles userRoles = userService.getUser(username, true);
        Set<String> roleNames = new HashSet<>(userRoles.getRoles());

        if (!roles.areRolesAuthorized(roleNames, loginPrivileges)) {
            // if we have default roles, grant the user the default roles
            if (!defaultRoles.isEmpty()) {
                roleNames = defaultRoles;

                // check that the default role names make sense
                if (!roles.areRolesAuthorized(roleNames, loginPrivileges)) {
                    throw new BadCredentialsException("Bad credentials");
                }
            } else {
                throw new BadCredentialsException("Bad credentials");
            }
        }

        final Collection<GrantedAuthority> grantedAuthorities = roleNames.stream()
                .map(SimpleGrantedAuthority::new).collect(Collectors.toList());

        final Collection<? extends GrantedAuthority> mappedAuthorities = authoritiesMapper
                .mapAuthorities(grantedAuthorities);

        return new UsernamePasswordAuthenticationToken(
                new CommunityPrincipal(userRoles.getUid(), username, userRoles.getSecurityInfo(), roleNames),
                password, mappedAuthorities);
    } catch (final AciErrorException aciError) {
        // This should not happen
        throw new InternalAuthenticationServiceException(
                "An ACI error occurred while attempting to authenticate", aciError);
    } catch (final AciServiceException serviceError) {
        // This will happen if community is down
        throw new InternalAuthenticationServiceException("An error occurred while contacting community",
                serviceError);
    }
}

From source file:org.artifactory.security.ldap.ArtifactoryLdapAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) {
    String userName = authentication.getName();
    // If it's an anonymous user, don't bother searching for the user.
    if (UserInfo.ANONYMOUS.equals(userName)) {
        return null;
    }/*www  .ja va  2  s  . c  om*/

    log.debug("Trying to authenticate user '{}' via ldap.", userName);
    LdapSetting usedLdapSetting = null;
    DirContextOperations user = null;
    AddonsManager addonsManager = InternalContextHelper.get().beanForType(AddonsManager.class);
    LdapGroupAddon ldapGroupAddon = addonsManager.addonByType(LdapGroupAddon.class);
    try {
        RuntimeException authenticationException = null;
        for (Map.Entry<String, BindAuthenticator> entry : authenticator.getAuthenticators().entrySet()) {
            LdapSetting currentLdapSetting = centralConfig.getDescriptor().getSecurity()
                    .getLdapSettings(entry.getKey());
            BindAuthenticator bindAuthenticator = entry.getValue();
            try {
                user = bindAuthenticator.authenticate(authentication);
                if (user != null) {
                    usedLdapSetting = currentLdapSetting;
                    break;
                }
            } catch (AuthenticationException e) {
                authenticationException = e;
                checkIfBindAndSearchActive(currentLdapSetting, userName);
            } catch (org.springframework.security.core.AuthenticationException e) {
                authenticationException = e;
                checkIfBindAndSearchActive(currentLdapSetting, userName);
            } catch (RuntimeException e) {
                authenticationException = e;
            }
        }
        if (user == null) {
            if (authenticationException != null) {
                UserInfo userInfo = userGroupService.findUser(userName);
                if (userInfo != null) {
                    log.debug("user {} failed to perform ldap authentication (not bad credential)",
                            userInfo.getUsername());
                    removeUserLdapRelatedGroups(userInfo);
                }
                throw authenticationException;
            }
            throw new AuthenticationServiceException(ArtifactoryLdapAuthenticator.LDAP_SERVICE_MISCONFIGURED);
        }

        // user authenticated via ldap
        log.debug("'{}' authenticated successfully by ldap server.", userName);

        //Collect internal groups, and if using external groups add them to the user info
        MutableUserInfo userInfo = InfoFactoryHolder.get().copyUser(
                userGroupService.findOrCreateExternalAuthUser(userName, !usedLdapSetting.isAutoCreateUser()));
        userInfo.setRealm(LdapService.REALM);
        String emailAttribute = usedLdapSetting.getEmailAttribute();
        if (StringUtils.isNotBlank(emailAttribute)) {
            String email = user.getStringAttribute(emailAttribute);
            if (StringUtils.isNotBlank(email)) {
                log.debug("User '{}' has email address '{}'", userName, email);
                userInfo.setEmail(email);
            }
        }

        log.debug("Loading LDAP groups");
        ldapGroupAddon.populateGroups(user, userInfo);
        log.debug("Finished Loading LDAP groups");
        SimpleUser simpleUser = new SimpleUser(userInfo);

        // update user with latest attribute
        userGroupService.updateUser(userInfo, false);

        // create new authentication response containing the user and it's authorities
        return new LdapRealmAwareAuthentication(simpleUser, authentication.getCredentials(),
                simpleUser.getAuthorities());
    } catch (AuthenticationException e) {
        String message = String.format("Failed to authenticate user '%s' via LDAP: %s", userName,
                e.getMessage());
        log.debug(message);
        throw new AuthenticationServiceException(message, e);
    } catch (CommunicationException ce) {
        String message = String.format("Failed to authenticate user '%s' via LDAP: communication error",
                userName);
        log.warn(message);
        log.debug(message, ce);
        throw new AuthenticationServiceException(message, ce);
    } catch (org.springframework.security.core.AuthenticationException e) {
        String message = String.format("Failed to authenticate user '%s' via LDAP: %s", userName,
                e.getMessage());
        log.debug(message);
        throw e;
    } catch (NamingException e) {
        String message = String.format("Failed to locate directory entry for authenticated user: %s",
                e.getMostSpecificCause().getMessage());
        log.debug(message);
        throw new AuthenticationServiceException(message, e);
    } catch (InvalidNameException e) {
        String message = String.format("Failed to persist user '%s': %s", userName, e.getMessage());
        log.warn(message);
        log.debug("Cause: {}", e);
        throw new InternalAuthenticationServiceException(message, e);
    } catch (Exception e) {
        String message = "Unexpected exception in LDAP authentication:";
        log.error(message, e);
        throw new AuthenticationServiceException(message, e);
    } finally {
        LdapUtils.closeContext(user);
    }
}

From source file:org.cloudfoundry.identity.uaa.security.CsrfAwareEntryPointAndDeniedHandler.java

protected void internalHandle(HttpServletRequest request, HttpServletResponse response, Exception exception)
        throws IOException, ServletException {
    AuthenticationException authEx = (exception instanceof AuthenticationException)
            ? (AuthenticationException) exception
            : new InternalAuthenticationServiceException("Access denied.", exception);

    if (wantJson(request)) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().append(String.format("{\"error\":\"%s\"}", exception.getMessage()));
    } else {/*ww  w. j  a va  2  s .c om*/
        LoginUrlAuthenticationEntryPoint entryPoint = getLoginUrlAuthenticationEntryPoint(exception);
        entryPoint.commence(request, response, authEx);
    }
}

From source file:org.jasig.ssp.service.security.lti.impl.LtiConsumerServiceImpl.java

@Override
public ConsumerDetails loadConsumerByConsumerKey(String consumerKey) throws OAuthException {
    // ConsumerDetailsService contract requires that this method must
    // not return null. All failures must be represented by OAuthException.
    final LtiConsumer consumer;
    try {/*from w ww. j  a  va  2 s.co  m*/
        consumer = findByConsumerKey(consumerKey);
        if (consumer == null) {
            throw new ObjectNotFoundException(consumerKey, LtiConsumer.class.getName());
        }

        // Technically you might be loading the consumer for other reasons that don't
        // have to do with processing an authentication request, but in practice that's
        // all we use this method for. So in order to avoid any possibly holes whereby
        // a disabled LtiConsumer successfully authenticates requests, we put that sort
        // of checking here rather than in processLaunch()
        if (consumer.getObjectStatus() != ObjectStatus.ACTIVE) {
            throw new ConsumerDetailsDisabledException(
                    "Consumer with key [" + consumerKey + "] has been disabled");
        }
        if (StringUtils.isBlank(consumer.getSecret())) {
            throw new ConsumerDetailsDisabledException(
                    "Consumer with key [" + consumerKey + "] has been disabled because it has no secret");
        }

        // Wrap in the same try catch b/c there's no semantic collision currently between
        // the possible exception types thrown by lookup and initialization ops, and
        // we're doing our best to ensure all failures are represented a OAuthException as
        // required by the contract
        BaseConsumerDetails consumerDetails = new BaseConsumerDetails();
        consumerDetails.setConsumerKey(consumer.getConsumerKey());
        consumerDetails.setSignatureSecret(new SharedConsumerSecretImpl(consumer.getSecret()));
        consumerDetails.setRequiredToObtainAuthenticatedToken(false);
        return consumerDetails;
    } catch (ObjectNotFoundException e) {
        // contract requires an OAuthException for all failures, including any sort of disabled/missing consumer
        throw new ConsumerDetailsNotFoundException("Failed to load consumer by key [" + consumerKey + "]", e);
    } catch (OAuthException e) {
        throw e;
    } catch (AuthenticationException e) {
        // Shouldn't happen, but if it does, it's probably not a InternalAuthenticationServiceException
        // as handled below. And we can be fairly sure the issue isn't a missing Consumer. So just... disabled.
        throw new ConsumerDetailsDisabledException("Failed to load consumer by key [" + consumerKey + "]", e);
    } catch (Exception e) {
        final InternalAuthenticationServiceException ssWrap = new InternalAuthenticationServiceException(
                "Failed to load consumer by key [" + consumerKey + "]", e);
        throw new OAuthException("Failed to load consumer by key [" + consumerKey + "]", ssWrap);
    }

}