Search in sources :

Example 1 with LockedException

use of org.springframework.security.authentication.LockedException 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 2 with LockedException

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

the class ResetControllerTest method shouldSetUserBlockedFlag.

@Test
public void shouldSetUserBlockedFlag() throws Exception {
    when(motechUserService.changeExpiredPassword(USER, PASSWORD, NEW_PASSWORD)).thenThrow(new LockedException("User has been blocked!"));
    controller.perform(post("/changepassword").locale(Locale.ENGLISH).body(new ObjectMapper().writeValueAsBytes(getPasswordForm(USER, PASSWORD, NEW_PASSWORD, NEW_PASSWORD))).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(new ObjectMapper().writeValueAsString(getChangePasswordViewData(false, true, new ArrayList<String>(), getPasswordForm(EMPTY, EMPTY, EMPTY, EMPTY)))));
    verify(motechUserService).changeExpiredPassword(USER, PASSWORD, NEW_PASSWORD);
}
Also used : LockedException(org.springframework.security.authentication.LockedException) ArrayList(java.util.ArrayList) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) Test(org.junit.Test)

Example 3 with LockedException

use of org.springframework.security.authentication.LockedException in project open-kilda by telstra.

the class LoginController method authenticate.

/**
 * Authenticate.
 *
 * @param username the username
 * @param password the password
 * @param request the request
 * @return the model and view
 */
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public ModelAndView authenticate(@RequestParam("username") String username, @RequestParam("password") final String password, final HttpServletRequest request, RedirectAttributes redir) {
    ModelAndView modelAndView = new ModelAndView(IConstants.View.LOGIN);
    String error = null;
    username = username != null ? username.toLowerCase() : null;
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
    CustomWebAuthenticationDetails customWebAuthenticationDetails = new CustomWebAuthenticationDetails(request);
    token.setDetails(customWebAuthenticationDetails);
    try {
        HttpSession sessionOld = request.getSession(false);
        if (sessionOld != null && !sessionOld.isNew()) {
            sessionOld.invalidate();
        }
        Authentication authenticate = authenticationManager.authenticate(token);
        if (authenticate.isAuthenticated()) {
            modelAndView.setViewName(IConstants.View.REDIRECT_HOME);
            UserInfo userInfo = getLoggedInUser(request);
            userService.populateUserInfo(userInfo, username);
            request.getSession(true).setAttribute(IConstants.SESSION_OBJECT, userInfo);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            userService.updateLoginDetail(username);
        } else {
            error = "Login failed; Invalid email or password.";
            LOGGER.warn("Authentication failure for user: '" + username + "'");
            modelAndView.setViewName(IConstants.View.REDIRECT_LOGIN);
        }
    } catch (TwoFaKeyNotSetException e) {
        LOGGER.warn("2 FA Key not set for user: '" + username + "'");
        modelAndView.addObject("username", username);
        modelAndView.addObject("password", password);
        String secretKey = TwoFactorUtility.getBase32EncryptedKey();
        modelAndView.addObject("key", secretKey);
        userService.updateUser2FaKey(username, secretKey);
        modelAndView.addObject("applicationName", applicationName);
        modelAndView.setViewName(IConstants.View.TWO_FA_GENERATOR);
    } catch (OtpRequiredException e) {
        LOGGER.warn("OTP required for user: '" + username + "'");
        modelAndView.addObject("username", username);
        modelAndView.addObject("password", password);
        modelAndView.addObject("applicationName", applicationName);
        modelAndView.setViewName(IConstants.View.OTP);
    } catch (InvalidOtpException e) {
        LOGGER.warn("Authentication code is invalid for user: '" + username + "'");
        error = "Authentication code is invalid";
        modelAndView.addObject("username", username);
        modelAndView.addObject("password", password);
        modelAndView.addObject("applicationName", applicationName);
        if (customWebAuthenticationDetails.isConfigure2Fa()) {
            UserEntity userInfo = userService.getUserByUsername(username);
            modelAndView.addObject("key", userInfo.getTwoFaKey());
            modelAndView.setViewName(IConstants.View.TWO_FA_GENERATOR);
        } else {
            modelAndView.setViewName(IConstants.View.OTP);
        }
    } catch (BadCredentialsException e) {
        LOGGER.warn("Authentication failure", e);
        error = e.getMessage();
        modelAndView.setViewName(IConstants.View.REDIRECT_LOGIN);
    } catch (LockedException e) {
        error = e.getMessage();
        modelAndView.setViewName(IConstants.View.REDIRECT_LOGIN);
    } catch (Exception e) {
        LOGGER.warn("Authentication failure", e);
        error = "Login Failed. Error: " + e.getMessage() + ".";
        modelAndView.setViewName(IConstants.View.REDIRECT_LOGIN);
    }
    if (error != null) {
        redir.addFlashAttribute("error", error);
    }
    return modelAndView;
}
Also used : LockedException(org.springframework.security.authentication.LockedException) CustomWebAuthenticationDetails(org.openkilda.security.CustomWebAuthenticationDetails) HttpSession(javax.servlet.http.HttpSession) ModelAndView(org.springframework.web.servlet.ModelAndView) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) UserInfo(org.usermanagement.model.UserInfo) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) TwoFaKeyNotSetException(org.openkilda.exception.TwoFaKeyNotSetException) OtpRequiredException(org.openkilda.exception.OtpRequiredException) UserEntity(org.usermanagement.dao.entity.UserEntity) OtpRequiredException(org.openkilda.exception.OtpRequiredException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) LockedException(org.springframework.security.authentication.LockedException) InvalidOtpException(org.openkilda.exception.InvalidOtpException) TwoFaKeyNotSetException(org.openkilda.exception.TwoFaKeyNotSetException) Authentication(org.springframework.security.core.Authentication) InvalidOtpException(org.openkilda.exception.InvalidOtpException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with LockedException

use of org.springframework.security.authentication.LockedException in project open-kilda by telstra.

the class CustomAuthenticationProvider method updateInvalidLoginAttempts.

private String updateInvalidLoginAttempts(UserEntity entity, String value, String accUnlockTime) {
    Integer loginCount = entity.getFailedLoginCount();
    if (loginCount != null) {
        if (loginCount + 1 >= Integer.valueOf(value)) {
            entity.setFailedLoginCount(loginCount + 1);
            entity.setUnlockTime(Integer.valueOf(accUnlockTime));
            entity.setFailedLoginTime(new Timestamp(System.currentTimeMillis()));
            entity.setStatusEntity(Status.getStatusByCode(Status.LOCK.getCode()).getStatusEntity());
            userRepository.save(entity);
            try {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", entity.getName());
                map.put("time", accUnlockTime);
                mailService.send(entity.getEmail(), mailUtils.getSubjectAccountBlock(), TemplateService.Template.ACCOUNT_BLOCK, map);
            } catch (Exception e) {
                LOGGER.warn("User account block email failed for username:'" + entity.getUsername());
            }
            throw new LockedException("User account is locked for " + Integer.valueOf(accUnlockTime) + " minute(s)");
        }
        entity.setFailedLoginCount(loginCount + 1);
    } else {
        entity.setFailedLoginCount(1);
    }
    int attempts = Integer.valueOf(value) - entity.getFailedLoginCount();
    String error = "Invalid email or password.You are left with " + attempts + " more attempts.";
    userRepository.save(entity);
    return error;
}
Also used : LockedException(org.springframework.security.authentication.LockedException) HashMap(java.util.HashMap) Timestamp(java.sql.Timestamp) OtpRequiredException(org.openkilda.exception.OtpRequiredException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) LockedException(org.springframework.security.authentication.LockedException) TwoFaKeyNotSetException(org.openkilda.exception.TwoFaKeyNotSetException) InvalidOtpException(org.openkilda.exception.InvalidOtpException)

Example 5 with LockedException

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

the class ResourceOwnerPasswordTokenGranterTests method testAccountLocked.

@Test(expected = InvalidGrantException.class)
public void testAccountLocked() {
    ResourceOwnerPasswordTokenGranter granter = new ResourceOwnerPasswordTokenGranter(new AuthenticationManager() {

        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            throw new LockedException("test");
        }
    }, providerTokenServices, clientDetailsService, requestFactory);
    granter.grant("password", tokenRequest);
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) LockedException(org.springframework.security.authentication.LockedException) AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) Test(org.junit.Test)

Aggregations

LockedException (org.springframework.security.authentication.LockedException)15 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)8 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)7 Authentication (org.springframework.security.core.Authentication)5 HttpSession (javax.servlet.http.HttpSession)3 AuthenticationException (org.springframework.security.core.AuthenticationException)3 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)2 AccountLockedException (com.haulmont.cuba.security.global.AccountLockedException)2 LoginException (com.haulmont.cuba.security.global.LoginException)2 Timestamp (java.sql.Timestamp)2 Locale (java.util.Locale)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 Test (org.junit.Test)2 Test (org.junit.jupiter.api.Test)2 InvalidOtpException (org.openkilda.exception.InvalidOtpException)2 OtpRequiredException (org.openkilda.exception.OtpRequiredException)2 TwoFaKeyNotSetException (org.openkilda.exception.TwoFaKeyNotSetException)2 AuthenticationCredentialsNotFoundException (org.springframework.security.authentication.AuthenticationCredentialsNotFoundException)2 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)2 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)1