Search in sources :

Example 46 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project motech by motech.

the class MotechLoginErrorHandlerTest method shouldBlockUser.

@Test
public void shouldBlockUser() throws ServletException, IOException {
    AuthenticationException exception = new BadCredentialsException("Wrong Password");
    exception.setAuthentication(authentication);
    MotechUser user = createUser(UserStatus.ACTIVE, 3);
    when(authentication.getName()).thenReturn("testUser");
    when(motechUsersDao.findByUserName("testUser")).thenReturn(user);
    when(settingService.getFailureLoginLimit()).thenReturn(3);
    motechLoginErrorHandler.onAuthenticationFailure(request, response, exception);
    verify(response).sendRedirect(LOGIN_BLOCKED);
    verify(motechUsersDao).update(userCaptor.capture());
    MotechUser capturedUser = userCaptor.getValue();
    assertEquals((Integer) 0, capturedUser.getFailureLoginCounter());
    assertEquals(UserStatus.BLOCKED, capturedUser.getUserStatus());
}
Also used : MotechUser(org.motechproject.security.domain.MotechUser) AuthenticationException(org.springframework.security.core.AuthenticationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.Test)

Example 47 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project motech by motech.

the class MotechLoginErrorHandlerTest method shouldReturnJSON.

@Test
public void shouldReturnJSON() throws ServletException, IOException {
    AuthenticationException exception = new BadCredentialsException("Wrong Password");
    exception.setAuthentication(authentication);
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.addHeader("x-requested-with", "XMLHttpRequest");
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    motechLoginErrorHandler.onAuthenticationFailure(mockRequest, mockResponse, exception);
    MotechJsonMessage messageObject = new MotechJsonMessage("security.wrongPassword");
    assertEquals(messageObject.toJson(), mockResponse.getContentAsString());
}
Also used : MotechJsonMessage(org.motechproject.commons.api.json.MotechJsonMessage) AuthenticationException(org.springframework.security.core.AuthenticationException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 48 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project motech by motech.

the class MotechLoginErrorHandler method onAuthenticationFailure.

@Override
@Transactional
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
    // Wrong password or username
    if (exception instanceof BadCredentialsException) {
        MotechUser motechUser = motechUsersDao.findByUserName(exception.getAuthentication().getName());
        int failureLoginLimit = settingService.getFailureLoginLimit();
        if (motechUser != null && failureLoginLimit > 0) {
            int failureLoginCounter = motechUser.getFailureLoginCounter();
            failureLoginCounter++;
            if (failureLoginCounter > failureLoginLimit && motechUser.isActive()) {
                motechUser.setUserStatus(UserStatus.BLOCKED);
                failureLoginCounter = 0;
                LOGGER.debug("User {} has been blocked", motechUser.getUserName());
            }
            motechUser.setFailureLoginCounter(failureLoginCounter);
            motechUsersDao.update(motechUser);
        }
        if (motechUser != null && !motechUser.isActive()) {
            LOGGER.debug("Redirecting to " + userBlockedUrl);
            redirectStrategy.sendRedirect(request, response, userBlockedUrl);
            return;
        }
    }
    super.onAuthenticationFailure(request, response, exception);
}
Also used : MotechUser(org.motechproject.security.domain.MotechUser) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 49 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project ma-core-public by infiniteautomation.

the class MangoPasswordAuthenticationProvider method authenticate.

/* (non-Javadoc)
	 * @see org.springframework.security.authentication.AuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
	 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!(authentication instanceof UsernamePasswordAuthenticationToken)) {
        return null;
    }
    UserDetails userDetails = this.userDetailsService.loadUserByUsername(authentication.getName());
    this.userDetailsChecker.check(userDetails);
    // Validating the password against the database.
    if (!Common.checkPassword((String) authentication.getCredentials(), userDetails.getPassword())) {
        throw new BadCredentialsException(Common.translate("login.validation.invalidLogin"));
    }
    if (!(userDetails instanceof User)) {
        throw new InternalAuthenticationServiceException("Expected user details to be instance of User");
    }
    return new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), Collections.unmodifiableCollection(userDetails.getAuthorities()));
}
Also used : UserDetails(org.springframework.security.core.userdetails.UserDetails) User(com.serotonin.m2m2.vo.User) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 50 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project ma-core-public by infiniteautomation.

the class MangoTokenAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!(authentication instanceof BearerAuthenticationToken)) {
        return null;
    }
    String bearerToken = (String) authentication.getCredentials();
    User user;
    Jws<Claims> jws;
    try {
        jws = tokenAuthenticationService.parse(bearerToken);
        user = tokenAuthenticationService.verify(jws);
    } catch (ExpiredJwtException e) {
        throw new CredentialsExpiredException(e.getMessage(), e);
    } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e) {
        // assume that this is not a JWT, allow the next AuthenticationProvider to process it
        return null;
    } catch (SignatureException | MissingClaimException | IncorrectClaimException e) {
        throw new BadCredentialsException(e.getMessage(), e);
    } catch (NotFoundException e) {
        throw new BadCredentialsException("Invalid username", e);
    } catch (Exception e) {
        throw new InternalAuthenticationServiceException(e.getMessage(), e);
    }
    userDetailsChecker.check(user);
    if (log.isDebugEnabled()) {
        log.debug("Successfully authenticated user using JWT token, header: " + jws.getHeader() + ", body: " + jws.getBody());
    }
    return new PreAuthenticatedAuthenticationToken(user, bearerToken, user.getAuthorities());
}
Also used : User(com.serotonin.m2m2.vo.User) Claims(io.jsonwebtoken.Claims) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) CredentialsExpiredException(org.springframework.security.authentication.CredentialsExpiredException) NotFoundException(com.serotonin.m2m2.vo.exception.NotFoundException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) SignatureException(io.jsonwebtoken.SignatureException) IncorrectClaimException(io.jsonwebtoken.IncorrectClaimException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) NotFoundException(com.serotonin.m2m2.vo.exception.NotFoundException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) MissingClaimException(io.jsonwebtoken.MissingClaimException) IncorrectClaimException(io.jsonwebtoken.IncorrectClaimException) CredentialsExpiredException(org.springframework.security.authentication.CredentialsExpiredException) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) SignatureException(io.jsonwebtoken.SignatureException) AuthenticationException(org.springframework.security.core.AuthenticationException) MissingClaimException(io.jsonwebtoken.MissingClaimException) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException)

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