Search in sources :

Example 21 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security-oauth by spring-projects.

the class TokenEndpointAuthenticationFilter method doFilter.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;
    try {
        Authentication credentials = extractCredentials(request);
        if (credentials != null) {
            if (debug) {
                logger.debug("Authentication credentials found for '" + credentials.getName() + "'");
            }
            Authentication authResult = authenticationManager.authenticate(credentials);
            if (debug) {
                logger.debug("Authentication success: " + authResult.getName());
            }
            Authentication clientAuth = SecurityContextHolder.getContext().getAuthentication();
            if (clientAuth == null) {
                throw new BadCredentialsException("No client authentication found. Remember to put a filter upstream of the TokenEndpointAuthenticationFilter.");
            }
            Map<String, String> map = getSingleValueMap(request);
            map.put(OAuth2Utils.CLIENT_ID, clientAuth.getName());
            AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(map);
            authorizationRequest.setScope(getScope(request));
            if (clientAuth.isAuthenticated()) {
                // Ensure the OAuth2Authentication is authenticated
                authorizationRequest.setApproved(true);
            }
            OAuth2Request storedOAuth2Request = oAuth2RequestFactory.createOAuth2Request(authorizationRequest);
            SecurityContextHolder.getContext().setAuthentication(new OAuth2Authentication(storedOAuth2Request, authResult));
            onSuccessfulAuthentication(request, response, authResult);
        }
    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();
        if (debug) {
            logger.debug("Authentication request for failed: " + failed);
        }
        onUnsuccessfulAuthentication(request, response, failed);
        authenticationEntryPoint.commence(request, response, failed);
        return;
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 22 with BadCredentialsException

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

the class PasswordComparisonAuthenticator method authenticate.

// ~ Methods
// ========================================================================================================
public DirContextOperations authenticate(final Authentication authentication) {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects");
    // locate the user and check the password
    DirContextOperations user = null;
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();
    Iterator dns = getUserDns(username).iterator();
    SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());
    while (dns.hasNext() && user == null) {
        final String userDn = (String) dns.next();
        try {
            user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
        } catch (NameNotFoundException ignore) {
        }
    }
    if (user == null && getUserSearch() != null) {
        user = getUserSearch().searchForUser(username);
    }
    if (user == null) {
        throw new UsernameNotFoundException("User not found: " + username);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Performing LDAP compare of password attribute '" + passwordAttributeName + "' for user '" + user.getDn() + "'");
    }
    String encodedPassword = passwordEncoder.encodePassword(password, null);
    byte[] passwordBytes = encodedPassword.getBytes();
    if (!ldapTemplate.compare(user.getDn().toString(), passwordAttributeName, passwordBytes)) {
        throw new BadCredentialsException(messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
    }
    return user;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SpringSecurityLdapTemplate(org.springframework.security.ldap.SpringSecurityLdapTemplate) DirContextOperations(org.springframework.ldap.core.DirContextOperations) NameNotFoundException(org.springframework.ldap.NameNotFoundException) Iterator(java.util.Iterator) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 23 with BadCredentialsException

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

the class AuthenticationCheck method getADBindAuthentication.

private Authentication getADBindAuthentication(String ldapUrl, String bindDn, String bindPassword, String userName, String userPassword) {
    Authentication result = null;
    try {
        LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(ldapUrl);
        ldapContextSource.setUserDn(bindDn);
        ldapContextSource.setPassword(bindPassword);
        ldapContextSource.setReferral("follow");
        ldapContextSource.setCacheEnvironmentProperties(true);
        ldapContextSource.setAnonymousReadOnly(false);
        ldapContextSource.setPooled(true);
        ldapContextSource.afterPropertiesSet();
        String searchFilter = "(sAMAccountName={0})";
        FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(adDomain, searchFilter, ldapContextSource);
        userSearch.setSearchSubtree(true);
        BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
        bindAuthenticator.setUserSearch(userSearch);
        bindAuthenticator.afterPropertiesSet();
        LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator);
        if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
            final UserDetails principal = new User(userName, userPassword, grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths);
            result = ldapAuthenticationProvider.authenticate(finalAuthentication);
        }
    } catch (BadCredentialsException bce) {
        logFile.println("ERROR: LDAP Authentication Failed. Please verify values for ranger.admin.auth.sampleuser and " + "ranger.admin.auth.samplepassword\n");
    } catch (Exception e) {
        logFile.println("ERROR: LDAP Authentication Failed: " + e);
    }
    return result;
}
Also used : BindAuthenticator(org.springframework.security.ldap.authentication.BindAuthenticator) DefaultSpringSecurityContextSource(org.springframework.security.ldap.DefaultSpringSecurityContextSource) User(org.springframework.security.core.userdetails.User) LdapContextSource(org.springframework.ldap.core.support.LdapContextSource) 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) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) FilterBasedLdapUserSearch(org.springframework.security.ldap.search.FilterBasedLdapUserSearch) LdapAuthenticationProvider(org.springframework.security.ldap.authentication.LdapAuthenticationProvider)

Example 24 with BadCredentialsException

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

the class AuthenticationCheck method getLdapBindAuthentication.

private Authentication getLdapBindAuthentication(String ldapUrl, String bindDn, String bindPassword, String userName, String userPassword) {
    Authentication result = null;
    try {
        LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(ldapUrl);
        ldapContextSource.setUserDn(bindDn);
        ldapContextSource.setPassword(bindPassword);
        ldapContextSource.setReferral("follow");
        ldapContextSource.setCacheEnvironmentProperties(false);
        ldapContextSource.setAnonymousReadOnly(true);
        ldapContextSource.setPooled(true);
        ldapContextSource.afterPropertiesSet();
        DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(ldapContextSource, groupSearchBase);
        defaultLdapAuthoritiesPopulator.setGroupRoleAttribute(roleAttribute);
        defaultLdapAuthoritiesPopulator.setGroupSearchFilter(groupSearchFilter);
        defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true);
        String searchFilter = "(uid={0})";
        FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(adDomain, searchFilter, ldapContextSource);
        userSearch.setSearchSubtree(true);
        BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
        bindAuthenticator.setUserSearch(userSearch);
        String[] userDnPatterns = new String[] { userDnPattern };
        bindAuthenticator.setUserDnPatterns(userDnPatterns);
        bindAuthenticator.afterPropertiesSet();
        LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator, defaultLdapAuthoritiesPopulator);
        if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
            final UserDetails principal = new User(userName, userPassword, grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths);
            result = ldapAuthenticationProvider.authenticate(finalAuthentication);
        }
    } catch (BadCredentialsException bce) {
        logFile.println("ERROR: LDAP Authentication Failed. Please verify values for ranger.admin.auth.sampleuser and " + "ranger.admin.auth.samplepassword\n");
    } catch (Exception e) {
        logFile.println("ERROR: LDAP Authentication Failed: " + e);
    }
    return result;
}
Also used : BindAuthenticator(org.springframework.security.ldap.authentication.BindAuthenticator) DefaultSpringSecurityContextSource(org.springframework.security.ldap.DefaultSpringSecurityContextSource) User(org.springframework.security.core.userdetails.User) LdapContextSource(org.springframework.ldap.core.support.LdapContextSource) DefaultLdapAuthoritiesPopulator(org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator) 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) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) FilterBasedLdapUserSearch(org.springframework.security.ldap.search.FilterBasedLdapUserSearch) LdapAuthenticationProvider(org.springframework.security.ldap.authentication.LdapAuthenticationProvider)

Example 25 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project webofneeds by researchstudio-sat.

the class LinkedDataWebController method register.

@RequestMapping(value = "${uri.path.resource}", method = RequestMethod.POST, produces = { "text/plain" })
public ResponseEntity<String> register(@RequestParam("register") String registeredType, HttpServletRequest request) throws CertificateException, UnsupportedEncodingException {
    logger.debug("REGISTERING " + registeredType);
    PreAuthenticatedAuthenticationToken authentication = (PreAuthenticatedAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication instanceof PreAuthenticatedAuthenticationToken)) {
        throw new BadCredentialsException("Could not register: PreAuthenticatedAuthenticationToken expected");
    }
    // Object principal = authentication.getPrincipal();
    Object credentials = authentication.getCredentials();
    X509Certificate cert;
    if (credentials instanceof X509Certificate) {
        cert = (X509Certificate) credentials;
    } else {
        throw new BadCredentialsException("Could not register: expected to find a X509Certificate in the request");
    }
    try {
        if ("owner".equals(registeredType)) {
            String result = registrationServer.registerOwner(cert);
            logger.debug("successfully registered owner");
            return new ResponseEntity<>(result, HttpStatus.OK);
        }
        if ("node".equals(registeredType)) {
            String result = registrationServer.registerNode(cert);
            logger.debug("successfully registered node");
            return new ResponseEntity<>(result, HttpStatus.OK);
        } else {
            String supportedTypesMsg = "Request parameter error; supported 'register' parameter values: 'owner', 'node'";
            logger.debug(supportedTypesMsg);
            return new ResponseEntity<>(supportedTypesMsg, HttpStatus.BAD_REQUEST);
        }
    } catch (WonProtocolException e) {
        logger.info("Could not register " + registeredType, e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) WonProtocolException(won.protocol.exception.WonProtocolException) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) X509Certificate(java.security.cert.X509Certificate) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

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