Search in sources :

Example 1 with DisabledException

use of org.springframework.security.authentication.DisabledException in project ORCID-Source by ORCID.

the class OauthLoginController method authenticateAndAuthorize.

@RequestMapping(value = { "/oauth/custom/signin.json", "/oauth/custom/login.json" }, method = RequestMethod.POST)
@ResponseBody
public OauthAuthorizeForm authenticateAndAuthorize(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthAuthorizeForm form) {
    // Clean form errors
    form.setErrors(new ArrayList<String>());
    RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute(REQUEST_INFO_FORM);
    boolean willBeRedirected = false;
    if (form.getApproved()) {
        // Validate name and password
        validateUserNameAndPassword(form);
        if (form.getErrors().isEmpty()) {
            try {
                // Authenticate user
                copy2FAFields(form, request);
                Authentication auth = authenticateUser(request, form.getUserName().getValue(), form.getPassword().getValue());
                profileEntityManager.updateLastLoginDetails(auth.getName(), OrcidRequestUtil.getIpAddress(request));
                // Create authorization params
                SimpleSessionStatus status = new SimpleSessionStatus();
                Map<String, Object> model = new HashMap<String, Object>();
                Map<String, String> params = new HashMap<String, String>();
                Map<String, String> approvalParams = new HashMap<String, String>();
                fillOauthParams(requestInfoForm, params, approvalParams, form.getPersistentTokenEnabled(), form.isEmailAccessAllowed());
                // Authorize
                try {
                    authorizationEndpoint.authorize(model, params, status, auth);
                } catch (RedirectMismatchException rUriError) {
                    String redirectUri = this.getBaseUri() + REDIRECT_URI_ERROR;
                    // Set the client id
                    redirectUri = redirectUri.replace("{0}", requestInfoForm.getClientId());
                    // Set the response type if needed
                    if (!PojoUtil.isEmpty(requestInfoForm.getResponseType()))
                        redirectUri += "&response_type=" + requestInfoForm.getResponseType();
                    // Set the redirect uri
                    if (!PojoUtil.isEmpty(requestInfoForm.getRedirectUrl()))
                        redirectUri += "&redirect_uri=" + requestInfoForm.getRedirectUrl();
                    // Set the scope param
                    if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()))
                        redirectUri += "&scope=" + requestInfoForm.getScopesAsString();
                    // Copy the state param if present
                    if (!PojoUtil.isEmpty(requestInfoForm.getStateParam()))
                        redirectUri += "&state=" + requestInfoForm.getStateParam();
                    form.setRedirectUrl(redirectUri);
                    LOGGER.info("OauthLoginController being sent to client browser: " + form.getRedirectUrl());
                    return form;
                }
                // Approve
                RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
                form.setRedirectUrl(view.getUrl());
                willBeRedirected = true;
            } catch (AuthenticationException ae) {
                if (ae.getCause() instanceof DisabledException) {
                    // Handle this message in angular to allow AJAX action
                    form.getErrors().add("orcid.frontend.security.orcid_deactivated");
                } else if (ae.getCause() instanceof UnclaimedProfileExistsException) {
                    String email = PojoUtil.isEmpty(form.getUserName()) ? null : form.getUserName().getValue();
                    String resendEmailUrl = createResendClaimUrl(email, request);
                    String errorMessage = getMessage("orcid.frontend.security.unclaimed_exists_1");
                    errorMessage += "<a href=\"" + resendEmailUrl + "\">";
                    errorMessage += getMessage("orcid.frontend.security.unclaimed_exists_2");
                    errorMessage += "</a>" + getMessage("orcid.frontend.security.unclaimed_exists_3");
                    form.getErrors().add(errorMessage);
                } else if (ae instanceof VerificationCodeFor2FARequiredException) {
                    form.setVerificationCodeRequired(true);
                } else if (ae instanceof Bad2FAVerificationCodeException) {
                    form.getErrors().add(getMessage("orcid.frontend.security.2fa.bad_verification_code"));
                } else if (ae instanceof Bad2FARecoveryCodeException) {
                    form.getErrors().add(getMessage("orcid.frontend.security.2fa.bad_recovery_code"));
                } else {
                    form.getErrors().add(getMessage("orcid.frontend.security.bad_credentials"));
                }
            }
        }
    } else {
        form.setRedirectUrl(buildDenyRedirectUri(requestInfoForm.getRedirectUrl(), requestInfoForm.getStateParam()));
        willBeRedirected = true;
    }
    // not be redirected yet
    if (willBeRedirected) {
        if (new HttpSessionRequestCache().getRequest(request, response) != null)
            new HttpSessionRequestCache().removeRequest(request, response);
        LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: " + requestInfoForm.getRedirectUrl());
    }
    return form;
}
Also used : HashMap(java.util.HashMap) AuthenticationException(org.springframework.security.core.AuthenticationException) DisabledException(org.springframework.security.authentication.DisabledException) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) Bad2FAVerificationCodeException(org.orcid.frontend.web.exception.Bad2FAVerificationCodeException) UnclaimedProfileExistsException(org.orcid.core.security.UnclaimedProfileExistsException) VerificationCodeFor2FARequiredException(org.orcid.frontend.web.exception.VerificationCodeFor2FARequiredException) Bad2FARecoveryCodeException(org.orcid.frontend.web.exception.Bad2FARecoveryCodeException) Authentication(org.springframework.security.core.Authentication) RedirectMismatchException(org.springframework.security.oauth2.common.exceptions.RedirectMismatchException) RedirectView(org.springframework.web.servlet.view.RedirectView) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) SimpleSessionStatus(org.springframework.web.bind.support.SimpleSessionStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 2 with DisabledException

use of org.springframework.security.authentication.DisabledException in project syncope by apache.

the class AuthDataAccessor method authenticate.

@Transactional
public Pair<String, Set<SyncopeGrantedAuthority>> authenticate(final JWTAuthentication authentication) {
    String username;
    Set<SyncopeGrantedAuthority> authorities;
    if (adminUser.equals(authentication.getClaims().getSubject())) {
        AccessToken accessToken = accessTokenDAO.find(authentication.getClaims().getTokenId());
        if (accessToken == null) {
            throw new AuthenticationCredentialsNotFoundException("Could not find an Access Token for JWT " + authentication.getClaims().getTokenId());
        }
        username = adminUser;
        authorities = getAdminAuthorities();
    } else {
        JWTSSOProvider jwtSSOProvider = getJWTSSOProvider(authentication.getClaims().getIssuer());
        Pair<User, Set<SyncopeGrantedAuthority>> resolved = jwtSSOProvider.resolve(authentication.getClaims());
        if (resolved == null || resolved.getLeft() == null) {
            throw new AuthenticationCredentialsNotFoundException("Could not find User " + authentication.getClaims().getSubject() + " for JWT " + authentication.getClaims().getTokenId());
        }
        User user = resolved.getLeft();
        username = user.getUsername();
        authorities = resolved.getRight() == null ? Collections.emptySet() : resolved.getRight();
        LOG.debug("JWT {} issued by {} resolved to User {} with authorities {}", authentication.getClaims().getTokenId(), authentication.getClaims().getIssuer(), username, authorities);
        if (BooleanUtils.isTrue(user.isSuspended())) {
            throw new DisabledException("User " + username + " is suspended");
        }
        Optional<? extends CPlainAttr> authStatuses = confDAO.find("authentication.statuses");
        if (authStatuses.isPresent() && !authStatuses.get().getValuesAsStrings().contains(user.getStatus())) {
            throw new DisabledException("User " + username + " not allowed to authenticate");
        }
        if (BooleanUtils.isTrue(user.isMustChangePassword())) {
            LOG.debug("User {} must change password, resetting authorities", username);
            authorities = Collections.singleton(new SyncopeGrantedAuthority(StandardEntitlement.MUST_CHANGE_PASSWORD));
        }
    }
    return Pair.of(username, authorities);
}
Also used : AuthenticationCredentialsNotFoundException(org.springframework.security.authentication.AuthenticationCredentialsNotFoundException) User(org.apache.syncope.core.persistence.api.entity.user.User) Set(java.util.Set) HashSet(java.util.HashSet) AccessToken(org.apache.syncope.core.persistence.api.entity.AccessToken) DisabledException(org.springframework.security.authentication.DisabledException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 3 with DisabledException

use of org.springframework.security.authentication.DisabledException in project syncope by apache.

the class AuthDataAccessor method authenticate.

/**
 * Attempts to authenticate the given credentials against internal storage and pass-through resources (if
 * configured): the first succeeding causes global success.
 *
 * @param authentication given credentials
 * @return {@code null} if no matching user was found, authentication result otherwise
 */
@Transactional(noRollbackFor = DisabledException.class)
public Pair<User, Boolean> authenticate(final Authentication authentication) {
    User user = null;
    Optional<? extends CPlainAttr> authAttrs = confDAO.find("authentication.attributes");
    List<String> authAttrValues = authAttrs.isPresent() ? authAttrs.get().getValuesAsStrings() : Collections.singletonList("username");
    for (int i = 0; user == null && i < authAttrValues.size(); i++) {
        if ("username".equals(authAttrValues.get(i))) {
            user = userDAO.findByUsername(authentication.getName());
        } else {
            AttributeCond attrCond = new AttributeCond(AttributeCond.Type.EQ);
            attrCond.setSchema(authAttrValues.get(i));
            attrCond.setExpression(authentication.getName());
            List<User> users = searchDAO.search(SearchCond.getLeafCond(attrCond), AnyTypeKind.USER);
            if (users.size() == 1) {
                user = users.get(0);
            } else {
                LOG.warn("Value {} provided for {} does not uniquely identify a user", authentication.getName(), authAttrValues.get(i));
            }
        }
    }
    Boolean authenticated = null;
    if (user != null) {
        authenticated = false;
        if (user.isSuspended() != null && user.isSuspended()) {
            throw new DisabledException("User " + user.getUsername() + " is suspended");
        }
        Optional<? extends CPlainAttr> authStatuses = confDAO.find("authentication.statuses");
        if (authStatuses.isPresent() && !authStatuses.get().getValuesAsStrings().contains(user.getStatus())) {
            throw new DisabledException("User " + user.getUsername() + " not allowed to authenticate");
        }
        boolean userModified = false;
        authenticated = AuthDataAccessor.this.authenticate(user, authentication.getCredentials().toString());
        if (authenticated) {
            if (confDAO.find("log.lastlogindate", true)) {
                user.setLastLoginDate(new Date());
                userModified = true;
            }
            if (user.getFailedLogins() != 0) {
                user.setFailedLogins(0);
                userModified = true;
            }
        } else {
            user.setFailedLogins(user.getFailedLogins() + 1);
            userModified = true;
        }
        if (userModified) {
            userDAO.save(user);
        }
    }
    return ImmutablePair.of(user, authenticated);
}
Also used : User(org.apache.syncope.core.persistence.api.entity.user.User) AttributeCond(org.apache.syncope.core.persistence.api.dao.search.AttributeCond) DisabledException(org.springframework.security.authentication.DisabledException) Date(java.util.Date) Transactional(org.springframework.transaction.annotation.Transactional)

Example 4 with DisabledException

use of org.springframework.security.authentication.DisabledException in project irida by phac-nml.

the class CredentialsExpiredAuthenticationFailureHandlerTest method testOnAuthenticationFailureWithOtherException.

@Test
public void testOnAuthenticationFailureWithOtherException() throws IOException, ServletException {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    AuthenticationException exception = new DisabledException("disabled");
    handler.onAuthenticationFailure(request, response, exception);
    verifyZeroInteractions(userService);
    verifyZeroInteractions(resetService);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(org.springframework.security.core.AuthenticationException) DisabledException(org.springframework.security.authentication.DisabledException) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.junit.Test)

Example 5 with DisabledException

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

the class LoginController method initForm.

@RequestMapping(method = RequestMethod.GET)
public String initForm(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("login") LoginForm loginForm, BindingResult result) {
    BindException errors = new BindException(result);
    HttpSession session = request.getSession(false);
    if (session != null) {
        AuthenticationException ex = (AuthenticationException) session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        if (ex != null) {
            if (ex instanceof DisabledException) {
                errors.reject("login.validation.accountDisabled", ex.getMessage());
            } else {
                errors.reject("login.validation.invalidLogin", ex.getMessage());
            }
        }
        String username = (String) session.getAttribute("username");
        if (username != null && !username.isEmpty()) {
            loginForm.setUsername(username);
        }
    }
    return "/WEB-INF/jsp/login.jsp";
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) DisabledException(org.springframework.security.authentication.DisabledException) BindException(org.springframework.validation.BindException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

DisabledException (org.springframework.security.authentication.DisabledException)15 Test (org.junit.jupiter.api.Test)4 AuthenticationException (org.springframework.security.core.AuthenticationException)4 UserType (com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)2 User (org.apache.syncope.core.persistence.api.entity.user.User)2 UnclaimedProfileExistsException (org.orcid.core.security.UnclaimedProfileExistsException)2 Bad2FARecoveryCodeException (org.orcid.frontend.web.exception.Bad2FARecoveryCodeException)2 Bad2FAVerificationCodeException (org.orcid.frontend.web.exception.Bad2FAVerificationCodeException)2 VerificationCodeFor2FARequiredException (org.orcid.frontend.web.exception.VerificationCodeFor2FARequiredException)2 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)2 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)2 AuthenticationCredentialsNotFoundException (org.springframework.security.authentication.AuthenticationCredentialsNotFoundException)2 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)2 Authentication (org.springframework.security.core.Authentication)2 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)2 Transactional (org.springframework.transaction.annotation.Transactional)2 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)2 APIKeyAuthFilter (alfio.config.authentication.support.APIKeyAuthFilter)1 APITokenAuthentication (alfio.config.authentication.support.APITokenAuthentication)1 RequestTypeMatchers (alfio.config.authentication.support.RequestTypeMatchers)1