Search in sources :

Example 26 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project cuba by cuba-platform.

the class CubaUserAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String ipAddress = request.getRemoteAddr();
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        RestApiConfig config = configuration.getConfig(RestApiConfig.class);
        if (!config.getStandardAuthenticationEnabled()) {
            log.debug("Standard authentication is disabled. Property cuba.rest.standardAuthenticationEnabled is false");
            throw new InvalidGrantException("Authentication disabled");
        }
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        String login = (String) token.getPrincipal();
        UserSession session;
        try {
            String passwordHash = passwordEncryption.getPlainHash((String) token.getCredentials());
            LoginPasswordCredentials credentials = new LoginPasswordCredentials(login, passwordHash);
            credentials.setIpAddress(ipAddress);
            credentials.setClientType(ClientType.REST_API);
            credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));
            // if the locale value is explicitly passed in the Accept-Language header then set its value to the
            // credentials. Otherwise, the locale of the user should be used
            Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request);
            if (locale != null) {
                credentials.setLocale(locale);
                credentials.setOverrideLocale(true);
            } else {
                credentials.setOverrideLocale(false);
            }
            session = authenticationService.login(credentials).getSession();
        } catch (AccountLockedException le) {
            log.info("Blocked user login attempt: login={}, ip={}", login, ipAddress);
            throw new LockedException("User temporarily blocked");
        } catch (RestApiAccessDeniedException ex) {
            log.info("User is not allowed to use the REST API {}", login);
            throw new BadCredentialsException("User is not allowed to use the REST API");
        } catch (LoginException e) {
            log.info("REST API authentication failed: {} {}", login, ipAddress);
            throw new BadCredentialsException("Bad credentials");
        }
        AppContext.setSecurityContext(new SecurityContext(session));
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), getRoleUserAuthorities(authentication));
        @SuppressWarnings("unchecked") Map<String, String> details = (Map<String, String>) authentication.getDetails();
        details.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString());
        result.setDetails(details);
        return result;
    }
    return null;
}
Also used : RestApiConfig(com.haulmont.restapi.config.RestApiConfig) Locale(java.util.Locale) AccountLockedException(com.haulmont.cuba.security.global.AccountLockedException) LockedException(org.springframework.security.authentication.LockedException) AccountLockedException(com.haulmont.cuba.security.global.AccountLockedException) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) LoginPasswordCredentials(com.haulmont.cuba.security.auth.LoginPasswordCredentials) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) LoginException(com.haulmont.cuba.security.global.LoginException) RestApiAccessDeniedException(com.haulmont.cuba.security.global.RestApiAccessDeniedException) Map(java.util.Map)

Example 27 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project ranger by apache.

the class RangerAuthenticationProvider method getJDBCAuthentication.

private Authentication getJDBCAuthentication(Authentication authentication, String encoder) throws AuthenticationException {
    try {
        ReflectionSaltSource saltSource = new ReflectionSaltSource();
        saltSource.setUserPropertyToUse("username");
        DaoAuthenticationProvider authenticator = new DaoAuthenticationProvider();
        authenticator.setUserDetailsService(userDetailsService);
        if (encoder != null && "SHA256".equalsIgnoreCase(encoder)) {
            authenticator.setPasswordEncoder(new ShaPasswordEncoder(256));
        } else if (encoder != null && "MD5".equalsIgnoreCase(encoder)) {
            authenticator.setPasswordEncoder(new Md5PasswordEncoder());
        }
        authenticator.setSaltSource(saltSource);
        String userName = "";
        String userPassword = "";
        if (authentication != null) {
            userName = authentication.getName();
            if (authentication.getCredentials() != null) {
                userPassword = authentication.getCredentials().toString();
            }
        }
        String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
        if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
            final UserDetails principal = new User(userName, userPassword, grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths);
            authentication = authenticator.authenticate(finalAuthentication);
            return authentication;
        } else {
            if (authentication != null && !authentication.isAuthenticated()) {
                throw new BadCredentialsException("Bad credentials");
            }
        }
    } catch (BadCredentialsException e) {
        throw e;
    } catch (AuthenticationServiceException e) {
        throw e;
    } catch (AuthenticationException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    }
    return authentication;
}
Also used : ShaPasswordEncoder(org.springframework.security.authentication.encoding.ShaPasswordEncoder) User(org.springframework.security.core.userdetails.User) AuthenticationException(org.springframework.security.core.AuthenticationException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.security.core.AuthenticationException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) ReflectionSaltSource(org.springframework.security.authentication.dao.ReflectionSaltSource) Md5PasswordEncoder(org.springframework.security.authentication.encoding.Md5PasswordEncoder) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(org.springframework.security.core.userdetails.UserDetails) DaoAuthenticationProvider(org.springframework.security.authentication.dao.DaoAuthenticationProvider) Authentication(org.springframework.security.core.Authentication)

Example 28 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project service-authorization by reportportal.

the class ActiveDirectoryAuthProvider method getDelegate.

@Override
protected AuthenticationProvider getDelegate() {
    ActiveDirectoryConfig adConfig = authConfigRepository.findActiveDirectory(true).orElseThrow(() -> new BadCredentialsException("Active Directory is not configured"));
    ActiveDirectoryLdapAuthenticationProvider adAuth = new ActiveDirectoryLdapAuthenticationProvider(adConfig.getDomain(), adConfig.getUrl(), adConfig.getBaseDn());
    adAuth.setAuthoritiesMapper(new NullAuthoritiesMapper());
    adAuth.setUserDetailsContextMapper(new DetailsContextMapper(ldapUserReplicator, adConfig.getSynchronizationAttributes()));
    return adAuth;
}
Also used : ActiveDirectoryConfig(com.epam.reportportal.auth.store.entity.ldap.ActiveDirectoryConfig) ActiveDirectoryLdapAuthenticationProvider(org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) NullAuthoritiesMapper(org.springframework.security.core.authority.mapping.NullAuthoritiesMapper)

Example 29 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project service-authorization by reportportal.

the class LdapAuthProvider method getDelegate.

@Override
protected AuthenticationProvider getDelegate() {
    LdapConfig ldap = authConfigRepository.findLdap(true).orElseThrow(() -> new BadCredentialsException("LDAP is not configured"));
    DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(singletonList(ldap.getUrl()), ldap.getBaseDn());
    ofNullable(ldap.getManagerPassword()).ifPresent(contextSource::setPassword);
    ofNullable(ldap.getManagerDn()).ifPresent(contextSource::setUserDn);
    contextSource.afterPropertiesSet();
    LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> builder = new LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder>().contextSource(contextSource).ldapAuthoritiesPopulator(new NullLdapAuthoritiesPopulator()).userDetailsContextMapper(new DetailsContextMapper(ldapUserReplicator, ldap.getSynchronizationAttributes()));
    /*
         * Basically, groups are not used
		 */
    ofNullable(ldap.getGroupSearchFilter()).ifPresent(builder::groupSearchFilter);
    ofNullable(ldap.getGroupSearchBase()).ifPresent(builder::groupSearchBase);
    ofNullable(ldap.getUserSearchFilter()).ifPresent(builder::userSearchFilter);
    ofNullable(ldap.getPasswordEncoderType()).ifPresent(it -> {
        LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder>.PasswordCompareConfigurer passwordCompareConfigurer = builder.passwordCompare();
        if (!isNullOrEmpty(ldap.getPasswordAttribute())) {
            passwordCompareConfigurer.passwordAttribute(ldap.getPasswordAttribute());
        }
        /*
			 * DIRTY HACK. If LDAP's password has solt, ldaptemplate.compare operation does not work
			 * since we don't know server's salt.
			 * To enable local password comparison, we need to provide password encoder from crypto's package
			 * This is why we just wrap old encoder with new one interface
			 * New encoder cannot be used everywhere since it does not have implementation for LDAP
			 */
        final PasswordEncoder delegate = ENCODER_MAPPING.get(ldap.getPasswordEncoderType());
        builder.passwordEncoder(new org.springframework.security.crypto.password.PasswordEncoder() {

            @Override
            public String encode(CharSequence rawPassword) {
                return delegate.encodePassword(rawPassword.toString(), null);
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return delegate.isPasswordValid(encodedPassword, rawPassword.toString(), null);
            }
        });
    });
    if (!isNullOrEmpty(ldap.getUserDnPattern())) {
        builder.userDnPatterns(ldap.getUserDnPattern());
    }
    try {
        return (AuthenticationProvider) Accessible.on(builder).method(LdapAuthenticationProviderConfigurer.class.getDeclaredMethod("build")).invoke();
    } catch (Throwable e) {
        throw new ReportPortalException("Cannot build LDAP auth provider", e);
    }
}
Also used : DefaultSpringSecurityContextSource(org.springframework.security.ldap.DefaultSpringSecurityContextSource) AuthenticationProvider(org.springframework.security.authentication.AuthenticationProvider) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) LdapConfig(com.epam.reportportal.auth.store.entity.ldap.LdapConfig) AuthenticationManagerBuilder(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder) ReportPortalException(com.epam.ta.reportportal.exception.ReportPortalException) NullLdapAuthoritiesPopulator(org.springframework.security.ldap.authentication.NullLdapAuthoritiesPopulator) LdapAuthenticationProviderConfigurer(org.springframework.security.config.annotation.authentication.configurers.ldap.LdapAuthenticationProviderConfigurer)

Example 30 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project nifi by apache.

the class LdapProvider method authenticate.

@Override
public final AuthenticationResponse authenticate(final LoginCredentials credentials) throws InvalidLoginCredentialsException, IdentityAccessException {
    if (provider == null) {
        throw new IdentityAccessException("The LDAP authentication provider is not initialized.");
    }
    try {
        // perform the authentication
        final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
        final Authentication authentication = provider.authenticate(token);
        // use dn if configured
        if (IdentityStrategy.USE_DN.equals(identityStrategy)) {
            // attempt to get the ldap user details to get the DN
            if (authentication.getPrincipal() instanceof LdapUserDetails) {
                final LdapUserDetails userDetails = (LdapUserDetails) authentication.getPrincipal();
                return new AuthenticationResponse(userDetails.getDn(), credentials.getUsername(), expiration, issuer);
            } else {
                logger.warn(String.format("Unable to determine user DN for %s, using username.", authentication.getName()));
                return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer);
            }
        } else {
            return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer);
        }
    } catch (final BadCredentialsException | UsernameNotFoundException | AuthenticationException e) {
        throw new InvalidLoginCredentialsException(e.getMessage(), e);
    } catch (final Exception e) {
        // there appears to be a bug that generates a InternalAuthenticationServiceException wrapped around an AuthenticationException. this
        // shouldn't be the case as they the service exception suggestions that something was wrong with the service. while the authentication
        // exception suggests that username and/or credentials were incorrect. checking the cause seems to address this scenario.
        final Throwable cause = e.getCause();
        if (cause instanceof AuthenticationException) {
            throw new InvalidLoginCredentialsException(e.getMessage(), e);
        }
        logger.error(e.getMessage());
        if (logger.isDebugEnabled()) {
            logger.debug(StringUtils.EMPTY, e);
        }
        throw new IdentityAccessException("Unable to validate the supplied credentials. Please contact the system administrator.", e);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) AuthenticationException(org.springframework.ldap.AuthenticationException) Authentication(org.springframework.security.core.Authentication) InvalidLoginCredentialsException(org.apache.nifi.authentication.exception.InvalidLoginCredentialsException) LdapUserDetails(org.springframework.security.ldap.userdetails.LdapUserDetails) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) IdentityAccessException(org.apache.nifi.authentication.exception.IdentityAccessException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationResponse(org.apache.nifi.authentication.AuthenticationResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.ldap.AuthenticationException) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) KeyStoreException(java.security.KeyStoreException) IdentityAccessException(org.apache.nifi.authentication.exception.IdentityAccessException) ProviderCreationException(org.apache.nifi.authentication.exception.ProviderCreationException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ProviderDestructionException(org.apache.nifi.authentication.exception.ProviderDestructionException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) InvalidLoginCredentialsException(org.apache.nifi.authentication.exception.InvalidLoginCredentialsException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Aggregations

BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)170 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)63 Authentication (org.springframework.security.core.Authentication)57 Test (org.junit.jupiter.api.Test)29 Test (org.junit.Test)27 AuthenticationException (org.springframework.security.core.AuthenticationException)23 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)20 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)20 UserDetails (org.springframework.security.core.userdetails.UserDetails)20 GrantedAuthority (org.springframework.security.core.GrantedAuthority)15 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)14 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)13 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)12 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 FilterChain (jakarta.servlet.FilterChain)10 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)10 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)9 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)7