Search in sources :

Example 21 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project pentaho-platform by pentaho.

the class SpringSecurityLoginModule method getAuthentication.

/**
 * {@inheritDoc}
 *
 * Creates a {@code UsernamePasswordAuthenticationToken} from the given {@code principal} and {@code credentials}
 * and passes to Spring Security {@code AuthenticationManager}.
 */
@Override
protected Authentication getAuthentication(final Principal principal, final Credentials credentials) throws RepositoryException {
    // only handles SimpleCredential instances; DefaultLoginModule behaves the same way (albeit indirectly)
    if (!(credentials instanceof SimpleCredentials)) {
        // $NON-NLS-1$
        logger.debug("credentials not instance of SimpleCredentials; returning null");
        return null;
    }
    SimpleCredentials simpleCredentials = (SimpleCredentials) credentials;
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(simpleCredentials.getUserID(), String.valueOf(simpleCredentials.getPassword()));
    boolean authenticated = false;
    try {
        org.springframework.security.core.Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getName().equals(simpleCredentials.getUserID())) {
            // see if there's already an active Authentication for this user.
            authenticated = true;
        } else {
            // delegate to Spring Security
            getAuthenticationManager().authenticate(token);
            authenticated = true;
        }
    } catch (AuthenticationException e) {
        // $NON-NLS-1$
        logger.debug("authentication exception", e);
    }
    final boolean authenticateResult = authenticated;
    return new Authentication() {

        public boolean canHandle(Credentials credentials) {
            // this is decided earlier in getAuthentication
            return true;
        }

        public boolean authenticate(Credentials credentials) throws RepositoryException {
            return authenticateResult;
        }
    };
}
Also used : SimpleCredentials(javax.jcr.SimpleCredentials) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.apache.jackrabbit.core.security.authentication.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) SimpleCredentials(javax.jcr.SimpleCredentials) Credentials(javax.jcr.Credentials)

Example 22 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project pentaho-platform by pentaho.

the class UserRoleDaoService method updatePassword.

public void updatePassword(User user, String administratorPassword) throws SecurityException {
    final IPentahoSession pentahoSession = PentahoSessionHolder.getSession();
    AuthenticationProvider authenticator = PentahoSystem.get(AuthenticationProvider.class, pentahoSession);
    if (authenticator == null) {
        throw new SecurityException("Authentication Provider not found, can not re-authenticate logged-in user");
    }
    try {
        Authentication authentication = authenticator.authenticate(new UsernamePasswordAuthenticationToken(pentahoSession.getName(), administratorPassword));
        if (authentication.isAuthenticated()) {
            updatePassword(user);
        } else {
            throw new SecurityException("Logged-in user re-authentication failed");
        }
    } catch (AuthenticationException e) {
        throw new SecurityException("Logged-in user re-authentication failed", e);
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) Authentication(org.springframework.security.core.Authentication) AuthenticationProvider(org.springframework.security.authentication.AuthenticationProvider) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 23 with AuthenticationException

use of org.springframework.security.core.AuthenticationException 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 24 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project ORCID-Source by ORCID.

the class ClaimController method automaticallyLogin.

private void automaticallyLogin(HttpServletRequest request, String password, String orcid) {
    UsernamePasswordAuthenticationToken token = null;
    try {
        token = new UsernamePasswordAuthenticationToken(orcid, password);
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (AuthenticationException e) {
        // this should never happen
        SecurityContextHolder.getContext().setAuthentication(null);
        LOGGER.warn("User " + orcid + " should have been logged-in, but we unable to due to a problem", e, (token != null ? token.getPrincipal() : "empty principle"));
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 25 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project ORCID-Source by ORCID.

the class ShibbolethController method post2FAVerificationCode.

@RequestMapping(value = { "/2FA/submitCode.json" }, method = RequestMethod.POST)
@ResponseBody
public TwoFactorAuthenticationCodes post2FAVerificationCode(@RequestBody TwoFactorAuthenticationCodes codes, HttpServletRequest request, HttpServletResponse response, @RequestHeader Map<String, String> headers) {
    checkEnabled();
    String shibIdentityProvider = headers.get(InstitutionalSignInManager.SHIB_IDENTITY_PROVIDER_HEADER);
    RemoteUser remoteUser = institutionalSignInManager.retrieveRemoteUser(headers);
    if (remoteUser == null) {
        LOGGER.info("Failed federated log in for {}", shibIdentityProvider);
        identityProviderManager.incrementFailedCount(shibIdentityProvider);
        codes.setRedirectUrl(orcidUrlManager.getBaseUrl() + "/shibboleth/signin");
        return codes;
    }
    UserconnectionEntity userConnectionEntity = userConnectionManager.findByProviderIdAndProviderUserIdAndIdType(remoteUser.getUserId(), shibIdentityProvider, remoteUser.getIdType());
    if (userConnectionEntity != null) {
        LOGGER.info("Found existing user connection: {}", userConnectionEntity);
        HeaderCheckResult checkHeadersResult = institutionalSignInManager.checkHeaders(parseOriginalHeaders(userConnectionEntity.getHeadersJson()), headers);
        if (!checkHeadersResult.isSuccess()) {
            codes.setRedirectUrl(orcidUrlManager.getBaseUrl() + "/shibboleth/signin");
            return codes;
        }
        validate2FACodes(userConnectionEntity.getOrcid(), codes);
        if (!codes.getErrors().isEmpty()) {
            return codes;
        }
        try {
            notifyUser(shibIdentityProvider, userConnectionEntity);
            processAuthentication(remoteUser, userConnectionEntity);
        } catch (AuthenticationException e) {
            // this should never happen
            SecurityContextHolder.getContext().setAuthentication(null);
            LOGGER.warn("User {0} should have been logged-in via Shibboleth, but was unable to due to a problem", remoteUser, e);
        }
        codes.setRedirectUrl(calculateRedirectUrl(request, response));
        return codes;
    } else {
        codes.setRedirectUrl(orcidUrlManager.getBaseUrl() + "/shibboleth/signin");
        return codes;
    }
}
Also used : HeaderCheckResult(org.orcid.pojo.HeaderCheckResult) RemoteUser(org.orcid.pojo.RemoteUser) AuthenticationException(org.springframework.security.core.AuthenticationException) UserconnectionEntity(org.orcid.persistence.jpa.entities.UserconnectionEntity) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

AuthenticationException (org.springframework.security.core.AuthenticationException)152 Authentication (org.springframework.security.core.Authentication)79 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)42 HttpServletRequest (javax.servlet.http.HttpServletRequest)26 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)24 HttpServletResponse (javax.servlet.http.HttpServletResponse)23 Test (org.junit.Test)20 Test (org.junit.jupiter.api.Test)19 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)14 IOException (java.io.IOException)13 ServletException (javax.servlet.ServletException)12 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)10 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)9 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)9 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)8 GrantedAuthority (org.springframework.security.core.GrantedAuthority)8 Map (java.util.Map)7 UserDetails (org.springframework.security.core.userdetails.UserDetails)7 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)6 HashMap (java.util.HashMap)6