Search in sources :

Example 96 with BadCredentialsException

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

the class CasAuthenticationProvider method authenticateNow.

private CasAuthenticationToken authenticateNow(final Authentication authentication) throws AuthenticationException {
    try {
        final Assertion assertion = this.ticketValidator.validate(authentication.getCredentials().toString(), getServiceUrl(authentication));
        final UserDetails userDetails = loadUserByAssertion(assertion);
        userDetailsChecker.check(userDetails);
        return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(), authoritiesMapper.mapAuthorities(userDetails.getAuthorities()), userDetails, assertion);
    } catch (final TicketValidationException e) {
        throw new BadCredentialsException(e.getMessage(), e);
    }
}
Also used : Assertion(org.jasig.cas.client.validation.Assertion) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) TicketValidationException(org.jasig.cas.client.validation.TicketValidationException)

Example 97 with BadCredentialsException

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

the class RemoteAuthenticationManagerImplTests method testFailedAuthenticationReturnsRemoteAuthenticationException.

// ~ Methods
// ========================================================================================================
@Test(expected = RemoteAuthenticationException.class)
public void testFailedAuthenticationReturnsRemoteAuthenticationException() {
    RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
    AuthenticationManager am = mock(AuthenticationManager.class);
    when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
    manager.setAuthenticationManager(am);
    manager.attemptAuthentication("rod", "password");
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) Authentication(org.springframework.security.core.Authentication) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.Test)

Example 98 with BadCredentialsException

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

the class BindAuthenticatorTests method testAuthenticationWithInvalidUserNameFails.

@Test
public void testAuthenticationWithInvalidUserNameFails() {
    this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
    try {
        this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("nonexistentsuser", "password"));
        fail("Shouldn't be able to bind with invalid username");
    } catch (BadCredentialsException expected) {
    }
}
Also used : UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.Test)

Example 99 with BadCredentialsException

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

the class DigestAuthenticationFilter method doFilter.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String header = request.getHeader("Authorization");
    if (header == null || !header.startsWith("Digest ")) {
        chain.doFilter(request, response);
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Digest Authorization header received from user agent: " + header);
    }
    DigestData digestAuth = new DigestData(header);
    try {
        digestAuth.validateAndDecode(this.authenticationEntryPoint.getKey(), this.authenticationEntryPoint.getRealmName());
    } catch (BadCredentialsException e) {
        fail(request, response, e);
        return;
    }
    // Lookup password for presented username
    // NB: DAO-provided password MUST be clear text - not encoded/salted
    // (unless this instance's passwordAlreadyEncoded property is 'false')
    boolean cacheWasUsed = true;
    UserDetails user = this.userCache.getUserFromCache(digestAuth.getUsername());
    String serverDigestMd5;
    try {
        if (user == null) {
            cacheWasUsed = false;
            user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
            if (user == null) {
                throw new AuthenticationServiceException("AuthenticationDao returned null, which is an interface contract violation");
            }
            this.userCache.putUserInCache(user);
        }
        serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
        // If digest is incorrect, try refreshing from backend and recomputing
        if (!serverDigestMd5.equals(digestAuth.getResponse()) && cacheWasUsed) {
            if (logger.isDebugEnabled()) {
                logger.debug("Digest comparison failure; trying to refresh user from DAO in case password had changed");
            }
            user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
            this.userCache.putUserInCache(user);
            serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
        }
    } catch (UsernameNotFoundException notFound) {
        fail(request, response, new BadCredentialsException(this.messages.getMessage("DigestAuthenticationFilter.usernameNotFound", new Object[] { digestAuth.getUsername() }, "Username {0} not found")));
        return;
    }
    // If digest is still incorrect, definitely reject authentication attempt
    if (!serverDigestMd5.equals(digestAuth.getResponse())) {
        if (logger.isDebugEnabled()) {
            logger.debug("Expected response: '" + serverDigestMd5 + "' but received: '" + digestAuth.getResponse() + "'; is AuthenticationDao returning clear text passwords?");
        }
        fail(request, response, new BadCredentialsException(this.messages.getMessage("DigestAuthenticationFilter.incorrectResponse", "Incorrect response")));
        return;
    }
    // but the request was otherwise appearing to be valid
    if (digestAuth.isNonceExpired()) {
        fail(request, response, new NonceExpiredException(this.messages.getMessage("DigestAuthenticationFilter.nonceExpired", "Nonce has expired/timed out")));
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Authentication success for user: '" + digestAuth.getUsername() + "' with response: '" + digestAuth.getResponse() + "'");
    }
    Authentication authentication = createSuccessfulAuthentication(request, user);
    SecurityContext context = SecurityContextHolder.createEmptyContext();
    context.setAuthentication(authentication);
    SecurityContextHolder.setContext(context);
    chain.doFilter(request, response);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) HttpServletResponse(javax.servlet.http.HttpServletResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext)

Example 100 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project opennms by OpenNMS.

the class SecurityAuthenticationEventOnmsEventBuilderTest method testAuthenticationFailureEvent.

public void testAuthenticationFailureEvent() throws Exception {
    String userName = "bar";
    String ip = "1.2.3.4";
    String sessionId = "it tastes just like our regular coffee";
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpSession session = createMock(HttpSession.class);
    expect(request.getRemoteAddr()).andReturn(ip);
    expect(request.getSession(false)).andReturn(session);
    expect(session.getId()).andReturn(sessionId);
    replay(request, session);
    WebAuthenticationDetails details = new WebAuthenticationDetails(request);
    verify(request, session);
    org.springframework.security.core.Authentication authentication = new TestingDetailsAuthenticationToken(userName, "cheesiness", new GrantedAuthority[0], details);
    AuthenticationFailureBadCredentialsEvent authEvent = new AuthenticationFailureBadCredentialsEvent(authentication, new BadCredentialsException("you are bad!"));
    SecurityAuthenticationEventOnmsEventBuilder builder = new SecurityAuthenticationEventOnmsEventBuilder();
    builder.setEventProxy(m_eventProxy);
    builder.afterPropertiesSet();
    EventBuilder eventBuilder = new EventBuilder(SecurityAuthenticationEventOnmsEventBuilder.FAILURE_UEI, "OpenNMS.WebUI");
    eventBuilder.addParam("user", userName);
    eventBuilder.addParam("ip", ip);
    eventBuilder.addParam("exceptionName", authEvent.getException().getClass().getSimpleName());
    eventBuilder.addParam("exceptionMessage", authEvent.getException().getMessage());
    m_eventProxy.send(EventEquals.eqEvent(eventBuilder.getEvent()));
    m_mocks.replayAll();
    builder.onApplicationEvent(authEvent);
    m_mocks.verifyAll();
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) EventBuilder(org.opennms.netmgt.model.events.EventBuilder) HttpSession(javax.servlet.http.HttpSession) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) AuthenticationFailureBadCredentialsEvent(org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Aggregations

BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)174 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)63 Authentication (org.springframework.security.core.Authentication)57 Test (org.junit.jupiter.api.Test)32 Test (org.junit.Test)26 AuthenticationException (org.springframework.security.core.AuthenticationException)24 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)22 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)21 UserDetails (org.springframework.security.core.userdetails.UserDetails)20 GrantedAuthority (org.springframework.security.core.GrantedAuthority)15 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)14 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)13 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)12 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