Search in sources :

Example 1 with UserAccountVO

use of com.cloud.user.UserAccountVO in project cloudstack by apache.

the class SAML2LoginAPIAuthenticatorCmd method authenticate.

@Override
public String authenticate(final String command, final Map<String, Object[]> params, final HttpSession session, final InetAddress remoteAddress, final String responseType, final StringBuilder auditTrailSb, final HttpServletRequest req, final HttpServletResponse resp) throws ServerApiException {
    try {
        if (!params.containsKey(SAMLPluginConstants.SAML_RESPONSE) && !params.containsKey("SAMLart")) {
            String idpId = null;
            String domainPath = null;
            if (params.containsKey(ApiConstants.IDP_ID)) {
                idpId = ((String[]) params.get(ApiConstants.IDP_ID))[0];
            }
            if (params.containsKey(ApiConstants.DOMAIN)) {
                domainPath = ((String[]) params.get(ApiConstants.DOMAIN))[0];
            }
            if (domainPath != null && !domainPath.isEmpty()) {
                if (!domainPath.startsWith("/")) {
                    domainPath = "/" + domainPath;
                }
                if (!domainPath.endsWith("/")) {
                    domainPath = domainPath + "/";
                }
            }
            SAMLProviderMetadata spMetadata = _samlAuthManager.getSPMetadata();
            SAMLProviderMetadata idpMetadata = _samlAuthManager.getIdPMetadata(idpId);
            if (idpMetadata == null) {
                throw new ServerApiException(ApiErrorCode.PARAM_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(), "IdP ID (" + idpId + ") is not found in our list of supported IdPs, cannot proceed.", params, responseType));
            }
            if (idpMetadata.getSsoUrl() == null || idpMetadata.getSsoUrl().isEmpty()) {
                throw new ServerApiException(ApiErrorCode.PARAM_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(), "IdP ID (" + idpId + ") has no Single Sign On URL defined please contact " + idpMetadata.getContactPersonName() + " <" + idpMetadata.getContactPersonEmail() + ">, cannot proceed.", params, responseType));
            }
            String authnId = SAMLUtils.generateSecureRandomId();
            _samlAuthManager.saveToken(authnId, domainPath, idpMetadata.getEntityId());
            s_logger.debug("Sending SAMLRequest id=" + authnId);
            String redirectUrl = SAMLUtils.buildAuthnRequestUrl(authnId, spMetadata, idpMetadata, SAML2AuthManager.SAMLSignatureAlgorithm.value());
            resp.sendRedirect(redirectUrl);
            return "";
        }
        if (params.containsKey("SAMLart")) {
            throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.UNSUPPORTED_ACTION_ERROR.getHttpCode(), "SAML2 HTTP Artifact Binding is not supported", params, responseType));
        } else {
            final String samlResponse = ((String[]) params.get(SAMLPluginConstants.SAML_RESPONSE))[0];
            Response processedSAMLResponse = this.processSAMLResponse(samlResponse);
            String statusCode = processedSAMLResponse.getStatus().getStatusCode().getValue();
            if (!statusCode.equals(StatusCode.SUCCESS_URI)) {
                throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Identity Provider send a non-successful authentication status code", params, responseType));
            }
            String username = null;
            Issuer issuer = processedSAMLResponse.getIssuer();
            SAMLProviderMetadata spMetadata = _samlAuthManager.getSPMetadata();
            SAMLProviderMetadata idpMetadata = _samlAuthManager.getIdPMetadata(issuer.getValue());
            String responseToId = processedSAMLResponse.getInResponseTo();
            s_logger.debug("Received SAMLResponse in response to id=" + responseToId);
            SAMLTokenVO token = _samlAuthManager.getToken(responseToId);
            if (token != null) {
                if (!(token.getEntity().equalsIgnoreCase(issuer.getValue()))) {
                    throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "The SAML response contains Issuer Entity ID that is different from the original SAML request", params, responseType));
                }
            } else {
                throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Received SAML response for a SSO request that we may not have made or has expired, please try logging in again", params, responseType));
            }
            // Set IdpId for this session
            session.setAttribute(SAMLPluginConstants.SAML_IDPID, issuer.getValue());
            Signature sig = processedSAMLResponse.getSignature();
            if (idpMetadata.getSigningCertificate() != null && sig != null) {
                BasicX509Credential credential = new BasicX509Credential();
                credential.setEntityCertificate(idpMetadata.getSigningCertificate());
                SignatureValidator validator = new SignatureValidator(credential);
                try {
                    validator.validate(sig);
                } catch (ValidationException e) {
                    s_logger.error("SAML Response's signature failed to be validated by IDP signing key:" + e.getMessage());
                    throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "SAML Response's signature failed to be validated by IDP signing key", params, responseType));
                }
            }
            if (username == null) {
                username = SAMLUtils.getValueFromAssertions(processedSAMLResponse.getAssertions(), SAML2AuthManager.SAMLUserAttributeName.value());
            }
            for (Assertion assertion : processedSAMLResponse.getAssertions()) {
                if (assertion != null && assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
                    session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue());
                    break;
                }
            }
            if (idpMetadata.getEncryptionCertificate() != null && spMetadata != null && spMetadata.getKeyPair() != null && spMetadata.getKeyPair().getPrivate() != null) {
                Credential credential = SecurityHelper.getSimpleCredential(idpMetadata.getEncryptionCertificate().getPublicKey(), spMetadata.getKeyPair().getPrivate());
                StaticKeyInfoCredentialResolver keyInfoResolver = new StaticKeyInfoCredentialResolver(credential);
                EncryptedKeyResolver keyResolver = new InlineEncryptedKeyResolver();
                Decrypter decrypter = new Decrypter(null, keyInfoResolver, keyResolver);
                decrypter.setRootInNewDocument(true);
                List<EncryptedAssertion> encryptedAssertions = processedSAMLResponse.getEncryptedAssertions();
                if (encryptedAssertions != null) {
                    for (EncryptedAssertion encryptedAssertion : encryptedAssertions) {
                        Assertion assertion = null;
                        try {
                            assertion = decrypter.decrypt(encryptedAssertion);
                        } catch (DecryptionException e) {
                            s_logger.warn("SAML EncryptedAssertion error: " + e.toString());
                        }
                        if (assertion == null) {
                            continue;
                        }
                        Signature encSig = assertion.getSignature();
                        if (idpMetadata.getSigningCertificate() != null && encSig != null) {
                            BasicX509Credential sigCredential = new BasicX509Credential();
                            sigCredential.setEntityCertificate(idpMetadata.getSigningCertificate());
                            SignatureValidator validator = new SignatureValidator(sigCredential);
                            try {
                                validator.validate(encSig);
                            } catch (ValidationException e) {
                                s_logger.error("SAML Response's signature failed to be validated by IDP signing key:" + e.getMessage());
                                throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "SAML Response's signature failed to be validated by IDP signing key", params, responseType));
                            }
                        }
                        if (assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
                            session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue());
                        }
                        if (username == null) {
                            username = SAMLUtils.getValueFromAttributeStatements(assertion.getAttributeStatements(), SAML2AuthManager.SAMLUserAttributeName.value());
                        }
                    }
                }
            }
            if (username == null) {
                throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Failed to find admin configured username attribute in the SAML Response. Please ask your administrator to check SAML user attribute name.", params, responseType));
            }
            UserAccount userAccount = null;
            List<UserAccountVO> possibleUserAccounts = _userAccountDao.getAllUsersByNameAndEntity(username, issuer.getValue());
            if (possibleUserAccounts != null && possibleUserAccounts.size() > 0) {
                // Users can switch to other allowed accounts later
                for (UserAccountVO possibleUserAccount : possibleUserAccounts) {
                    if (possibleUserAccount.getAccountState().equals(Account.State.enabled.toString())) {
                        userAccount = possibleUserAccount;
                        break;
                    }
                }
            }
            if (userAccount == null || userAccount.getExternalEntity() == null || !_samlAuthManager.isUserAuthorized(userAccount.getId(), issuer.getValue())) {
                throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Your authenticated user is not authorized for SAML Single Sign-On, please contact your administrator", params, responseType));
            }
            try {
                if (_apiServer.verifyUser(userAccount.getId())) {
                    LoginCmdResponse loginResponse = (LoginCmdResponse) _apiServer.loginUser(session, userAccount.getUsername(), userAccount.getUsername() + userAccount.getSource().toString(), userAccount.getDomainId(), null, remoteAddress, params);
                    SAMLUtils.setupSamlUserCookies(loginResponse, resp);
                    resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
                    return ApiResponseSerializer.toSerializedString(loginResponse, responseType);
                }
            } catch (CloudAuthenticationException | IOException exception) {
                s_logger.debug("SAML Login failed to log in the user due to: " + exception.getMessage());
            }
        }
    } catch (IOException e) {
        auditTrailSb.append("SP initiated SAML authentication using HTTP redirection failed:");
        auditTrailSb.append(e.getMessage());
    }
    throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Unable to authenticate user while performing SAML based SSO. Please make sure your user/account has been added, enable and authorized by the admin before you can authenticate. Please contact your administrator.", params, responseType));
}
Also used : ValidationException(org.opensaml.xml.validation.ValidationException) Issuer(org.opensaml.saml2.core.Issuer) SAMLTokenVO(org.apache.cloudstack.saml.SAMLTokenVO) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) StaticKeyInfoCredentialResolver(org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver) ServerApiException(org.apache.cloudstack.api.ServerApiException) SAMLProviderMetadata(org.apache.cloudstack.saml.SAMLProviderMetadata) BasicX509Credential(org.opensaml.xml.security.x509.BasicX509Credential) Credential(org.opensaml.xml.security.credential.Credential) Assertion(org.opensaml.saml2.core.Assertion) EncryptedAssertion(org.opensaml.saml2.core.EncryptedAssertion) Decrypter(org.opensaml.saml2.encryption.Decrypter) IOException(java.io.IOException) LoginCmdResponse(org.apache.cloudstack.api.response.LoginCmdResponse) Response(org.opensaml.saml2.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) UserAccountVO(com.cloud.user.UserAccountVO) BasicX509Credential(org.opensaml.xml.security.x509.BasicX509Credential) EncryptedAssertion(org.opensaml.saml2.core.EncryptedAssertion) Signature(org.opensaml.xml.signature.Signature) SignatureValidator(org.opensaml.xml.signature.SignatureValidator) InlineEncryptedKeyResolver(org.opensaml.xml.encryption.InlineEncryptedKeyResolver) DecryptionException(org.opensaml.xml.encryption.DecryptionException) UserAccount(com.cloud.user.UserAccount) LoginCmdResponse(org.apache.cloudstack.api.response.LoginCmdResponse) InlineEncryptedKeyResolver(org.opensaml.xml.encryption.InlineEncryptedKeyResolver) EncryptedKeyResolver(org.opensaml.xml.encryption.EncryptedKeyResolver)

Example 2 with UserAccountVO

use of com.cloud.user.UserAccountVO in project cloudstack by apache.

the class SAML2LoginAPIAuthenticatorCmdTest method testAuthenticate.

@Test
public void testAuthenticate() throws Exception {
    SAML2LoginAPIAuthenticatorCmd cmd = Mockito.spy(new SAML2LoginAPIAuthenticatorCmd());
    Field apiServerField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("_apiServer");
    apiServerField.setAccessible(true);
    apiServerField.set(cmd, apiServer);
    Field managerField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("_samlAuthManager");
    managerField.setAccessible(true);
    managerField.set(cmd, samlAuthManager);
    Field accountServiceField = BaseCmd.class.getDeclaredField("_accountService");
    accountServiceField.setAccessible(true);
    accountServiceField.set(cmd, accountService);
    Field domainMgrField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("_domainMgr");
    domainMgrField.setAccessible(true);
    domainMgrField.set(cmd, domainMgr);
    Field userAccountDaoField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("_userAccountDao");
    userAccountDaoField.setAccessible(true);
    userAccountDaoField.set(cmd, userAccountDao);
    KeyPair kp = SAMLUtils.generateRandomKeyPair();
    X509Certificate cert = SAMLUtils.generateRandomX509Certificate(kp);
    SAMLProviderMetadata providerMetadata = new SAMLProviderMetadata();
    providerMetadata.setEntityId("random");
    providerMetadata.setSigningCertificate(cert);
    providerMetadata.setEncryptionCertificate(cert);
    providerMetadata.setKeyPair(kp);
    providerMetadata.setSsoUrl("http://test.local");
    providerMetadata.setSloUrl("http://test.local");
    Mockito.when(session.getAttribute(Mockito.anyString())).thenReturn(null);
    Mockito.when(domain.getId()).thenReturn(1L);
    Mockito.when(domainMgr.getDomain(Mockito.anyString())).thenReturn(domain);
    UserAccountVO user = new UserAccountVO();
    user.setId(1000L);
    Mockito.when(userAccountDao.getUserAccount(Mockito.anyString(), Mockito.anyLong())).thenReturn(user);
    Mockito.when(apiServer.verifyUser(Mockito.anyLong())).thenReturn(false);
    Mockito.when(samlAuthManager.getSPMetadata()).thenReturn(providerMetadata);
    Mockito.when(samlAuthManager.getIdPMetadata(Mockito.anyString())).thenReturn(providerMetadata);
    Map<String, Object[]> params = new HashMap<String, Object[]>();
    // SSO redirection test
    cmd.authenticate("command", params, session, InetAddress.getByName("127.0.0.1"), HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    Mockito.verify(resp, Mockito.times(1)).sendRedirect(Mockito.anyString());
    // SSO SAMLResponse verification test, this should throw ServerApiException for auth failure
    params.put(SAMLPluginConstants.SAML_RESPONSE, new String[] { "Some String" });
    Mockito.stub(cmd.processSAMLResponse(Mockito.anyString())).toReturn(buildMockResponse());
    boolean failing = true;
    try {
        cmd.authenticate("command", params, session, InetAddress.getByName("127.0.0.1"), HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    } catch (ServerApiException ignored) {
        failing = false;
    }
    assertFalse("authentication should not have succeeded", failing);
    Mockito.verify(userAccountDao, Mockito.times(0)).getUserAccount(Mockito.anyString(), Mockito.anyLong());
    Mockito.verify(apiServer, Mockito.times(0)).verifyUser(Mockito.anyLong());
}
Also used : KeyPair(java.security.KeyPair) HashMap(java.util.HashMap) X509Certificate(java.security.cert.X509Certificate) Field(java.lang.reflect.Field) UserAccountVO(com.cloud.user.UserAccountVO) ServerApiException(org.apache.cloudstack.api.ServerApiException) SAMLProviderMetadata(org.apache.cloudstack.saml.SAMLProviderMetadata) Test(org.junit.Test)

Example 3 with UserAccountVO

use of com.cloud.user.UserAccountVO in project cloudstack by apache.

the class ListAndSwitchSAMLAccountCmdTest method testListAndSwitchSAMLAccountCmd.

@Test
public void testListAndSwitchSAMLAccountCmd() throws Exception {
    // Setup
    final Map<String, Object[]> params = new HashMap<String, Object[]>();
    final String sessionKeyValue = "someSessionIDValue";
    Mockito.when(session.getAttribute(ApiConstants.SESSIONKEY)).thenReturn(sessionKeyValue);
    Mockito.when(session.getAttribute("userid")).thenReturn(2L);
    params.put(ApiConstants.USER_ID, new String[] { "2" });
    params.put(ApiConstants.DOMAIN_ID, new String[] { "1" });
    Mockito.when(userDao.findByUuid(Mockito.anyString())).thenReturn(new UserVO(2L));
    Mockito.when(domainDao.findByUuid(Mockito.anyString())).thenReturn(new DomainVO());
    // Mock/field setup
    ListAndSwitchSAMLAccountCmd cmd = new ListAndSwitchSAMLAccountCmd();
    Field apiServerField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_apiServer");
    apiServerField.setAccessible(true);
    apiServerField.set(cmd, apiServer);
    Field managerField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_samlAuthManager");
    managerField.setAccessible(true);
    managerField.set(cmd, samlAuthManager);
    Field accountServiceField = BaseCmd.class.getDeclaredField("_accountService");
    accountServiceField.setAccessible(true);
    accountServiceField.set(cmd, accountService);
    Field userAccountDaoField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_userAccountDao");
    userAccountDaoField.setAccessible(true);
    userAccountDaoField.set(cmd, userAccountDao);
    Field userDaoField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_userDao");
    userDaoField.setAccessible(true);
    userDaoField.set(cmd, userDao);
    Field domainDaoField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_domainDao");
    domainDaoField.setAccessible(true);
    domainDaoField.set(cmd, domainDao);
    // invalid session test
    try {
        cmd.authenticate("command", params, null, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    } catch (ServerApiException exception) {
        assertEquals(exception.getErrorCode(), ApiErrorCode.UNAUTHORIZED);
    } finally {
        Mockito.verify(accountService, Mockito.times(0)).getUserAccountById(Mockito.anyLong());
    }
    // invalid sessionkey value test
    params.put(ApiConstants.SESSIONKEY, new String[] { "someOtherValue" });
    try {
        Mockito.when(session.isNew()).thenReturn(false);
        cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    } catch (ServerApiException exception) {
        assertEquals(exception.getErrorCode(), ApiErrorCode.UNAUTHORIZED);
    } finally {
        Mockito.verify(accountService, Mockito.times(0)).getUserAccountById(Mockito.anyLong());
    }
    // valid sessionkey value test
    params.put(ApiConstants.SESSIONKEY, new String[] { sessionKeyValue });
    try {
        cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    } catch (ServerApiException exception) {
        assertEquals(exception.getErrorCode(), ApiErrorCode.ACCOUNT_ERROR);
    } finally {
        Mockito.verify(accountService, Mockito.times(1)).getUserAccountById(Mockito.anyLong());
    }
    // valid sessionkey, invalid useraccount type (non-saml) value test
    UserAccountVO mockedUserAccount = new UserAccountVO();
    mockedUserAccount.setId(2L);
    mockedUserAccount.setAccountState(Account.State.enabled.toString());
    mockedUserAccount.setUsername("someUsername");
    mockedUserAccount.setExternalEntity("some IDP ID");
    mockedUserAccount.setDomainId(0L);
    mockedUserAccount.setSource(User.Source.UNKNOWN);
    Mockito.when(accountService.getUserAccountById(Mockito.anyLong())).thenReturn(mockedUserAccount);
    try {
        cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    } catch (ServerApiException exception) {
        assertEquals(exception.getErrorCode(), ApiErrorCode.ACCOUNT_ERROR);
    } finally {
        // accountService should have been called twice by now, for this case and the case above
        Mockito.verify(accountService, Mockito.times(2)).getUserAccountById(Mockito.anyLong());
    }
    // all valid test
    mockedUserAccount.setSource(User.Source.SAML2);
    Mockito.when(accountService.getUserAccountById(Mockito.anyLong())).thenReturn(mockedUserAccount);
    Mockito.when(apiServer.verifyUser(Mockito.anyLong())).thenReturn(true);
    LoginCmdResponse loginCmdResponse = new LoginCmdResponse();
    loginCmdResponse.setUserId("1");
    loginCmdResponse.setDomainId("1");
    loginCmdResponse.setType("1");
    loginCmdResponse.setUsername("userName");
    loginCmdResponse.setAccount("someAccount");
    loginCmdResponse.setFirstName("firstName");
    loginCmdResponse.setLastName("lastName");
    loginCmdResponse.setSessionKey("newSessionKeyString");
    Mockito.when(apiServer.loginUser(Mockito.any(HttpSession.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyLong(), Mockito.anyString(), Mockito.any(InetAddress.class), Mockito.anyMap())).thenReturn(loginCmdResponse);
    try {
        cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    } catch (ServerApiException exception) {
        fail("SAML list and switch account API failed to pass for all valid data: " + exception.getMessage());
    } finally {
        // accountService should have been called 4 times by now, for this case twice and 2 for cases above
        Mockito.verify(accountService, Mockito.times(4)).getUserAccountById(Mockito.anyLong());
        Mockito.verify(resp, Mockito.times(1)).sendRedirect(Mockito.anyString());
    }
}
Also used : HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) DomainVO(com.cloud.domain.DomainVO) Field(java.lang.reflect.Field) UserAccountVO(com.cloud.user.UserAccountVO) UserVO(com.cloud.user.UserVO) ServerApiException(org.apache.cloudstack.api.ServerApiException) InetAddress(java.net.InetAddress) LoginCmdResponse(org.apache.cloudstack.api.response.LoginCmdResponse) Test(org.junit.Test)

Example 4 with UserAccountVO

use of com.cloud.user.UserAccountVO in project cloudstack by apache.

the class MD5UserAuthenticatorTest method authenticate.

@Test
public void authenticate() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    MD5UserAuthenticator authenticator = new MD5UserAuthenticator();
    Field daoField = MD5UserAuthenticator.class.getDeclaredField("_userAccountDao");
    daoField.setAccessible(true);
    daoField.set(authenticator, dao);
    UserAccountVO account = new UserAccountVO();
    account.setPassword("5f4dcc3b5aa765d61d8327deb882cf99");
    Mockito.when(dao.getUserAccount(Mockito.anyString(), Mockito.anyLong())).thenReturn(account);
    Pair<Boolean, ActionOnFailedAuthentication> pair = authenticator.authenticate("admin", "password", 1l, null);
    Assert.assertTrue(pair.first());
}
Also used : Field(java.lang.reflect.Field) UserAccountVO(com.cloud.user.UserAccountVO) ActionOnFailedAuthentication(com.cloud.server.auth.UserAuthenticator.ActionOnFailedAuthentication) Test(org.junit.Test)

Example 5 with UserAccountVO

use of com.cloud.user.UserAccountVO in project cloudstack by apache.

the class RegionsApiUtil method makeUserAccountAPICall.

/**
     * Makes an api call using region service end_point, api command and params
     * Returns UserAccount object on success
     * @param region
     * @param command
     * @param params
     * @return
     */
protected static UserAccount makeUserAccountAPICall(Region region, String command, List<NameValuePair> params) {
    try {
        String url = buildUrl(buildParams(command, params), region);
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        if (client.executeMethod(method) == 200) {
            InputStream is = method.getResponseBodyAsStream();
            XStream xstream = new XStream(new DomDriver());
            xstream.alias("useraccount", UserAccountVO.class);
            xstream.aliasField("id", UserAccountVO.class, "uuid");
            try (ObjectInputStream in = xstream.createObjectInputStream(is)) {
                return (UserAccountVO) in.readObject();
            } catch (IOException e) {
                s_logger.error(e.getMessage());
                return null;
            }
        } else {
            return null;
        }
    } catch (HttpException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (IOException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (ClassNotFoundException e) {
        s_logger.error(e.getMessage());
        return null;
    }
}
Also used : DomDriver(com.thoughtworks.xstream.io.xml.DomDriver) UserAccountVO(com.cloud.user.UserAccountVO) ObjectInputStream(java.io.ObjectInputStream) InputStream(java.io.InputStream) XStream(com.thoughtworks.xstream.XStream) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod) ObjectInputStream(java.io.ObjectInputStream)

Aggregations

UserAccountVO (com.cloud.user.UserAccountVO)10 Field (java.lang.reflect.Field)7 Test (org.junit.Test)7 ServerApiException (org.apache.cloudstack.api.ServerApiException)4 ActionOnFailedAuthentication (com.cloud.server.auth.UserAuthenticator.ActionOnFailedAuthentication)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 LoginCmdResponse (org.apache.cloudstack.api.response.LoginCmdResponse)3 CloudAuthenticationException (com.cloud.exception.CloudAuthenticationException)2 UserAccount (com.cloud.user.UserAccount)2 UserVO (com.cloud.user.UserVO)2 SAMLProviderMetadata (org.apache.cloudstack.saml.SAMLProviderMetadata)2 Domain (com.cloud.domain.Domain)1 DomainVO (com.cloud.domain.DomainVO)1 User (com.cloud.user.User)1 XStream (com.thoughtworks.xstream.XStream)1 DomDriver (com.thoughtworks.xstream.io.xml.DomDriver)1 InputStream (java.io.InputStream)1 ObjectInputStream (java.io.ObjectInputStream)1 InetAddress (java.net.InetAddress)1