/// <summary> /// Returns the credentials /// </summary> /// <returns></returns> private ICredential GetCredentials() { ICredential returnCredential = null; try { CredentialManager credentialMngr = CredentialManager.Instance; returnCredential = credentialMngr.GetCredentials(this.config, apiUsername); if (!string.IsNullOrEmpty(accessToken)) { IThirdPartyAuthorization toknAuthuthorization = new TokenAuthorization(accessToken, tokenSecret); if (returnCredential is SignatureCredential) { SignatureCredential sigCred = (SignatureCredential)returnCredential; sigCred.ThirdPartyAuthorization = toknAuthuthorization; } else if (returnCredential is CertificateCredential) { CertificateCredential certCred = (CertificateCredential)returnCredential; certCred.ThirdPartyAuthorization = toknAuthuthorization; } } } catch (System.Exception ex) { throw ex; } return(returnCredential); }
/// <summary> /// Processing for TokenAuthorization using SignatureCredential /// </summary> /// <param name="certCredential"></param> /// <param name="tokenAuthorize"></param> /// <returns></returns> protected override Dictionary <string, string> ProcessTokenAuthorization(CertificateCredential certCredential, TokenAuthorization tokenAuthorize) { Dictionary <string, string> headers = new Dictionary <string, string>(); try { OAuthGenerator signGenerator = new OAuthGenerator(certCredential.UserName, certCredential.Password); signGenerator.SetToken(tokenAuthorize.AccessToken); signGenerator.SetTokenSecret(tokenAuthorize.AccessTokenSecret); string tokenTimeStamp = Timestamp; signGenerator.SetTokenTimestamp(tokenTimeStamp); logger.DebugFormat("token = " + tokenAuthorize.AccessToken + " tokenSecret=" + tokenAuthorize.AccessTokenSecret + " uri=" + endpointUrl); signGenerator.SetRequestUri(endpointUrl); //Compute Signature string sign = signGenerator.ComputeSignature(); logger.DebugFormat("Permissions signature: " + sign); string authorization = "token=" + tokenAuthorize.AccessToken + ",signature=" + sign + ",timestamp=" + tokenTimeStamp; logger.DebugFormat("Authorization string: " + authorization); headers.Add(BaseConstants.PayPalAuthorizationPlatformHeader, authorization); } catch (OAuthException oex) { throw oex; } return(headers); }
/// <summary> /// Handle challenges for a secured resource by prompting for a client certificate /// </summary> public async Task <Credential> CreateCredentialAsync(CredentialRequestInfo info) { Credential credential = null; try { // Use the X509Store to get available certificates var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); var certificates = store.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true); // Ask the user to select a certificate to use certificates = X509Certificate2UI.SelectFromCollection(certificates, "Select Certificate", "Select the certificate to use for authentication.", X509SelectionFlag.SingleSelection); // Create a new CertificateCredential using the chosen certificate credential = new CertificateCredential(certificates[0]) { ServiceUri = SecuredPortalUrl }; } catch (Exception ex) { Debug.WriteLine("Exception: " + ex.Message); } // Return the CertificateCredential for the secured portal return(credential); }
/// <summary> /// Processing for TokenAuthorization using SignatureCredential /// </summary> /// <param name="certCredential"></param> /// <param name="toknAuthorization"></param> /// <returns></returns> protected override Dictionary <string, string> ProcessTokenAuthorization( CertificateCredential certCredential, TokenAuthorization toknAuthorization) { Dictionary <string, string> headers = new Dictionary <string, string>(); try { OAuthGenerator signGenerator = new OAuthGenerator(certCredential.UserName, certCredential.Password); signGenerator.setHTTPMethod(OAuthGenerator.HTTPMethod.POST); signGenerator.setToken(toknAuthorization.AccessToken); signGenerator.setTokenSecret(toknAuthorization.TokenSecret); string tokenTimeStamp = Timestamp; signGenerator.setTokenTimestamp(tokenTimeStamp); logger.Debug("token = " + toknAuthorization.AccessToken + " tokenSecret=" + toknAuthorization.TokenSecret + " uri=" + endpointURL); signGenerator.setRequestURI(endpointURL); //Compute Signature string sign = signGenerator.ComputeSignature(); logger.Debug("Permissions signature: " + sign); string authorization = "token=" + toknAuthorization.AccessToken + ",signature=" + sign + ",timestamp=" + tokenTimeStamp; logger.Debug("Authorization string: " + authorization); headers.Add(BaseConstants.PAYPAL_AUTHORIZATION_PLATFORM_HEADER, authorization); } catch (OAuthException ae) { throw ae; } return(headers); }
/// <summary> /// Returns the API Credentials /// </summary> /// <param name="apiUserName"></param> /// <returns></returns> public ICredential GetCredentials(Dictionary <string, string> config, string apiUserName) { ICredential credential = null; Account accnt = GetAccount(config, apiUserName); if (accnt == null) { throw new MissingCredentialException("Missing credentials for " + apiUserName); } if (!string.IsNullOrEmpty(accnt.APICertificate)) { CertificateCredential certCredential = new CertificateCredential(accnt.APIUsername, accnt.APIPassword, accnt.APICertificate, accnt.PrivateKeyPassword); certCredential.ApplicationID = accnt.ApplicationId; if (!string.IsNullOrEmpty(accnt.CertificateSubject)) { SubjectAuthorization subAuthorization = new SubjectAuthorization(accnt.CertificateSubject); certCredential.ThirdPartyAuthorization = subAuthorization; } credential = certCredential; } else { SignatureCredential signCredential = new SignatureCredential(accnt.APIUsername, accnt.APIPassword, accnt.APISignature); signCredential.ApplicationID = accnt.ApplicationId; if (!string.IsNullOrEmpty(accnt.SignatureSubject)) { SubjectAuthorization subjectAuthorization = new SubjectAuthorization(accnt.SignatureSubject); signCredential.ThirdPartyAuthorization = subjectAuthorization; } credential = signCredential; } ValidateCredentials(credential); return(credential); }
/// <summary> /// Handle challenges for a secured resource by prompting for a client certificate /// </summary> public async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info) { Credential credential = null; try { // Use the X509Store to get available certificates var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); var certificates = store.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true); // Ask the user to select a certificate to use certificates = X509Certificate2UI.SelectFromCollection(certificates, "Select Certificate", "Select the certificate to use for authentication.", X509SelectionFlag.SingleSelection); // Create a new CertificateCredential using the chosen certificate credential = new CertificateCredential(certificates[0]) { ServiceUri = SecuredPortalUrl }; } catch (Exception ex) { Debug.WriteLine("Exception: " + ex.Message); } // Return the CertificateCredential for the secured portal return credential; }
/// <summary> /// Performs CredSSP authentication. /// </summary> /// <param name="x509Cert">The certificate used by TLS.</param> /// <exception cref="IOException">Raised when attempting to read from/write to the remote connection which /// has been closed</exception> /// <exception cref="EndOfStreamException">Raised when the username or password doesn't match or authentication /// fails</exception> public void Authenticate(X509Certificate x509Cert, string principal) { if (principal == null) { throw new ArgumentNullException("principal"); } // Authenticated already, do nothing if (isAuthenticated) { return; } credential = new CertificateCredential(x509Cert); byte[] receivedBuffer = new byte[MaxBufferSize]; int bytesReceived = 0; // Dispose the context as it may be timed out if (context != null) { context.Dispose(); } context = new SspiServerSecurityContext( SecurityPackageType.CredSsp, credential, principal, attribute, SecurityTargetDataRepresentation.SecurityNativeDrep); // Get first token byte[] token = context.Token; // Credssp handshake while (context.NeedContinueProcessing) { // Get handshake resopnse bytesReceived = serverStream.Read(receivedBuffer, 0, receivedBuffer.Length); // The remote connection has been closed if (bytesReceived == 0) { throw new EndOfStreamException("Authentication failed: remote connection has been closed."); } byte[] inToken = new byte[bytesReceived]; Array.Copy(receivedBuffer, inToken, bytesReceived); // Get next token from response context.Accept(inToken); token = context.Token; if (token != null) { // Send handshake request serverStream.Write(token, 0, token.Length); } } isAuthenticated = true; }
private Task <Credential> CreateCertificateCredentialAsync(CredentialRequestInfo credentialRequestInfo) { var tcs = new TaskCompletionSource <Credential>(); var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); X509Certificate2Collection certificates; try { const string clientAuthOid = "1.3.6.1.5.5.7.3.2"; // Client Authentication OID store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); // Find Client Authentication certificate certificates = store.Certificates.Find(X509FindType.FindByApplicationPolicy, clientAuthOid, true); } catch (Exception) { certificates = null; } finally { store.Close(); } string url = credentialRequestInfo.ServiceUri; ServerInfo serverInfo = IdentityManager.Current.FindServerInfo(url); if (certificates != null && certificates.Count >= 1) { // Let the user select/validate the certificate string resourceName = GetResourceName(url); string server = serverInfo == null?Regex.Match(url, "http.?//[^/]*").ToString() : serverInfo.ServerUri; string message = resourceName == null ? string.Format("certificate required to access to {0}", server) : string.Format("certificate required to access {0} on {1}", resourceName, server); certificates = X509Certificate2UI.SelectFromCollection(certificates, null, message, X509SelectionFlag.SingleSelection); } if (certificates != null && certificates.Count > 0) { var credential = new CertificateCredential(certificates[0]) { ServiceUri = serverInfo == null ? url : serverInfo.ServerUri }; if (AllowSaveCredentials) { CredentialManager.AddCredential(credential); } tcs.TrySetResult(credential); } else { // Note : Error type is not that important since the error returned to the user is the initial HTTP error (Authorization Error) tcs.TrySetException(new System.Security.Authentication.AuthenticationException()); } return(tcs.Task); }
public void GenerateHeaderStrategyWithoutToken() { certHttpHeaderAuthStrategy = new CertificateHttpHeaderAuthStrategy(Constants.APIEndpointNVP); certCredential = new CertificateCredential("testusername", "testpassword", "sdk-cert.p12", "KJAERUGBLVF6Y"); Dictionary<string, string> header = certHttpHeaderAuthStrategy.GenerateHeaderStrategy(certCredential); string username = header[BaseConstants.PayPalSecurityUserIdHeader]; string password = header[BaseConstants.PayPalSecurityPasswordHeader]; Assert.AreEqual("testusername", username); Assert.AreEqual("testpassword", password); }
public void GenerateHeaderStrategyWithoutToken() { certHttpHeaderAuthStrategy = new CertificateHttpHeaderAuthStrategy(UnitTestConstants.APIEndpointNVP); certCredential = new CertificateCredential("testusername", "testpassword", "sdk-cert.p12", "KJAERUGBLVF6Y"); Dictionary <string, string> header = certHttpHeaderAuthStrategy.GenerateHeaderStrategy(certCredential); string username = header[BaseConstants.PAYPAL_SECURITY_USERID_HEADER]; string password = header[BaseConstants.PAYPAL_SECURITY_PASSWORD_HEADER]; Assert.AreEqual("testusername", username); Assert.AreEqual("testpassword", password); }
public void GenerateHeaderStrategyWithoutTokenTest() { certHttpHeaderAuthStrategy = new CertificateHttpHeaderAuthStrategy(Constants.APIEndpointNVP); certCredential = new CertificateCredential("testusername", "testpassword", "sdk-cert.p12", "KJAERUGBLVF6Y"); Dictionary <string, string> header = certHttpHeaderAuthStrategy.GenerateHeaderStrategy(certCredential); string username = header[BaseConstants.PayPalSecurityUserIdHeader]; string password = header[BaseConstants.PayPalSecurityPasswordHeader]; Assert.AreEqual("testusername", username); Assert.AreEqual("testpassword", password); }
public void GenerateHeaderStrategyToken() { certCredential = new CertificateCredential("testusername", "testpassword", "sdk-cert.p12", "KJAERUGBLVF6Y"); certSOAPHeaderAuthStrategy = new CertificateSOAPHeaderAuthStrategy(); TokenAuthorization toknAuthorization = new TokenAuthorization("accessToken", "tokenSecret"); certSOAPHeaderAuthStrategy.ThirdPartyAuthorization = toknAuthorization; string payload = certSOAPHeaderAuthStrategy.GenerateHeaderStrategy(certCredential); Assert.AreEqual("<ns:RequesterCredentials/>", payload); }
public void GenerateHeaderStrategyWithToken() { certHttpHeaderAuthStrategy = new CertificateHttpHeaderAuthStrategy(UnitTestConstants.APIEndpointSOAP); TokenAuthorization toknAuthorization = new TokenAuthorization(UnitTestConstants.AccessToken, UnitTestConstants.TokenSecret); CertificateCredential certCredential = new CertificateCredential("testusername", "testpassword", "sdk-cert.p12", "KJAERUGBLVF6Y", toknAuthorization); Dictionary <string, string> header = certHttpHeaderAuthStrategy.GenerateHeaderStrategy(certCredential); string authHeader = header[BaseConstants.PAYPAL_AUTHORIZATION_MERCHANT_HEADER]; string[] headers = authHeader.Split(','); Assert.AreEqual("token=" + UnitTestConstants.AccessToken, headers[0]); }
public void GenerateHeaderStrategyWithTokenTest() { certHttpHeaderAuthStrategy = new CertificateHttpHeaderAuthStrategy(Constants.APIEndpointSOAP); TokenAuthorization toknAuthorization = new TokenAuthorization(Constants.AccessToken, Constants.TokenSecret); certCredential = new CertificateCredential("testusername", "testpassword", "sdk-cert.p12", "KJAERUGBLVF6Y", toknAuthorization); Dictionary <string, string> header = certHttpHeaderAuthStrategy.GenerateHeaderStrategy(certCredential); string authHeader = header[BaseConstants.PayPalAuthorizationPlatformHeader]; string[] headers = authHeader.Split(','); Assert.AreEqual("token=" + Constants.AccessToken, headers[0]); }
/// <summary> /// Makes a request to API service /// </summary> /// <param name="apiCallHandler"></param> /// <returns></returns> public string MakeRequestUsing(IAPICallPreHandler apiCallHandler) { string responseString = string.Empty; string uri = apiCallHandler.GetEndpoint(); Dictionary <string, string> headers = apiCallHandler.GetHeaderMap(); string payload = apiCallHandler.GetPayload(); //Constructing HttpWebRequest object ConnectionManager connMngr = ConnectionManager.Instance; HttpWebRequest httpRequest = connMngr.GetConnection(this.config, uri); httpRequest.Method = RequestMethod; if (headers != null && headers.ContainsKey(BaseConstants.ContentTypeHeader)) { httpRequest.ContentType = headers[BaseConstants.ContentTypeHeader].Trim(); headers.Remove(BaseConstants.ContentTypeHeader); } if (headers != null && headers.ContainsKey(BaseConstants.UserAgentHeader)) { httpRequest.UserAgent = headers[BaseConstants.UserAgentHeader].Trim(); headers.Remove(BaseConstants.UserAgentHeader); } foreach (KeyValuePair <string, string> header in headers) { httpRequest.Headers.Add(header.Key, header.Value); } foreach (string headerName in httpRequest.Headers) { logger.DebugFormat(headerName + ":" + httpRequest.Headers[headerName]); } if (apiCallHandler.GetCredential() is CertificateCredential) { CertificateCredential certCredential = (CertificateCredential)apiCallHandler.GetCredential(); //Load the certificate into an X509Certificate2 object. if (((CertificateCredential)certCredential).PrivateKeyPassword.Trim() == string.Empty) { x509 = new X509Certificate2(((CertificateCredential)certCredential).CertificateFile); } else { x509 = new X509Certificate2(((CertificateCredential)certCredential).CertificateFile, ((CertificateCredential)certCredential).PrivateKeyPassword); } httpRequest.ClientCertificates.Add(x509); } HttpConnection connectionHttp = new HttpConnection(config); string response = connectionHttp.Execute(payload, httpRequest); return(response); }
/// <summary> /// Constructor /// </summary> /// <param name="packageType">Specifies the name of the security package with which these credentials will be used /// </param> /// <param name="serverCredential">The credential of server, if null, use default user account.</param> /// <param name="serverPrincipal">Server principal name</param> /// <param name="contextAttributes">Bit flags that specify the attributes required by the server to establish /// the context</param> /// <param name="targetDataRep">The data representation, such as byte ordering, on the target. This parameter /// can be either SECURITY_NATIVE_DREP or SECURITY_NETWORK_DREP.</param> public SspiServerSecurityContext( SecurityPackageType packageType, CertificateCredential serverCredential, string serverPrincipal, ServerSecurityContextAttribute contextAttributes, SecurityTargetDataRepresentation targetDataRep) { this.packageType = packageType; this.serverPrincipalName = serverPrincipal; this.securityContextAttributes = contextAttributes; this.targetDataRepresentaion = targetDataRep; this.AcquireCredentialsHandle(serverCredential); }
/// <summary> /// Validates the API Credentials /// </summary> /// <param name="apiCredentials"></param> private void ValidateCredentials(ICredential apiCredentials) { if (apiCredentials is SignatureCredential) { SignatureCredential credential = (SignatureCredential)apiCredentials; Validate(credential); } else if (apiCredentials is CertificateCredential) { CertificateCredential credential = (CertificateCredential)apiCredentials; Validate(credential); } }
public ICredential GetCredentials(string apiUserName) { if (apiUserName == null) { apiUserName = GetDefaultAccountName(); } if (this.cachedCredentials.ContainsKey(apiUserName)) { log.Debug("Returning cached credentials for " + apiUserName); return(this.cachedCredentials[apiUserName]); } else { ICredential pro = null; ConfigManager configMgr = ConfigManager.Instance; Account acc = configMgr.GetAccount(apiUserName); if (acc == null) { throw new MissingCredentialException("Missing credentials for " + apiUserName); } if (!string.IsNullOrEmpty(acc.APICertificate)) { CertificateCredential cred = new CertificateCredential(); cred.APIUsername = acc.APIUsername; cred.APIPassword = acc.APIPassword; cred.CertificateFile = acc.APICertificate; cred.PrivateKeyPassword = acc.PrivateKeyPassword; cred.ApplicationID = acc.ApplicationId; cred.CertificateSubject = acc.CertificateSubject; pro = cred; } else { SignatureCredential cred = new SignatureCredential(); cred.APIUsername = acc.APIUsername; cred.APIPassword = acc.APIPassword; cred.APISignature = acc.APISignature; cred.ApplicationID = acc.ApplicationId; cred.SignatureSubject = acc.SignatureSubject; pro = cred; } this.cachedCredentials.Add(apiUserName, pro); return(pro); } }
public DtlsServerSecurityContext( SecurityPackageType packageType, CertificateCredential serverCredential, string serverPrincipal, ServerSecurityContextAttribute contextAttributes, SecurityTargetDataRepresentation targetDataRep) { this.packageType = packageType; this.serverPrincipalName = serverPrincipal; this.securityContextAttributes = contextAttributes; this.targetDataRepresentaion = targetDataRep; this.Context = new Sspi.DtlsServerSecurityContext(packageType, serverCredential, serverPrincipal, contextAttributes, targetDataRep); }
public void GenerateHeaderStrategy() { certCredential = new CertificateCredential("testusername", "testpassword", "sdk-cert.p12", "KJAERUGBLVF6Y"); certSOAPHeaderAuthStrategy = new CertificateSOAPHeaderAuthStrategy(); string payload = certSOAPHeaderAuthStrategy.GenerateHeaderStrategy(certCredential); XmlDocument xmlDoc = GetXmlDocument(payload); XmlNodeList xmlNodeListUsername = xmlDoc.GetElementsByTagName("Username"); Assert.IsTrue(xmlNodeListUsername.Count > 0); Assert.AreEqual("testusername", xmlNodeListUsername[0].InnerXml); XmlNodeList xmlNodeListPassword = xmlDoc.GetElementsByTagName("Password"); Assert.IsTrue(xmlNodeListPassword.Count > 0); Assert.AreEqual("testpassword", xmlNodeListPassword[0].InnerXml); }
public void LoadCertificateCredential() { string apiUsername = Constants.CertificateAPIUserName; credentialMngr = CredentialManager.Instance; credential = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), apiUsername); Assert.IsNotNull(credential); Assert.IsInstanceOfType(credential, typeof(CertificateCredential)); CertificateCredential certCredential = (CertificateCredential)credential; Assert.AreEqual(apiUsername, certCredential.UserName); Assert.AreEqual(Constants.CertificateAPIPassword, certCredential.Password); Assert.AreEqual(Path.GetFileName(Constants.CertificatePath), Path.GetFileName(certCredential.CertificateFile)); Assert.AreEqual(Constants.CertificatePassword, certCredential.PrivateKeyPassword); Assert.AreEqual(Constants.ApplicationId, certCredential.ApplicationId); }
public void ObjectCreation() { CertificateCredential cred = new CertificateCredential(); cred.APIUsername = "******"; cred.APIPassword = "******"; cred.ApplicationID = "APP-1234ASDFG"; cred.CertificateFile = "/certs/sdk.p12"; cred.PrivateKeyPassword = "******"; Assert.AreEqual("username_api1.paypal.com", cred.APIUsername); Assert.AreEqual("QWERRTYUIOP", cred.APIPassword); Assert.AreEqual("APP-1234ASDFG", cred.ApplicationID); Assert.AreEqual("/certs/sdk.p12", cred.CertificateFile); Assert.AreEqual("password", cred.PrivateKeyPassword); }
public void LoadCertificateCredential() { string apiUsername = UnitTestConstants.CertificateAPIUserName; credentialMngr = CredentialManager.Instance; credential = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), apiUsername); Assert.NotNull(credential); Assert.IsInstanceOf(typeof(CertificateCredential), credential); CertificateCredential certCredential = (CertificateCredential)credential; Assert.AreEqual(apiUsername, certCredential.UserName); Assert.AreEqual(UnitTestConstants.CertificateAPIPassword, certCredential.Password); Assert.AreEqual(UnitTestConstants.CertificatePath, certCredential.CertificateFile); Assert.AreEqual(UnitTestConstants.CertificatePassword, certCredential.PrivateKeyPassword); Assert.AreEqual(UnitTestConstants.ApplicationID, certCredential.ApplicationID); }
public void loadCertificateCredential() { string apiUsername = "******"; CredentialManager mgr = CredentialManager.Instance; ICredential cred = mgr.GetCredentials(apiUsername); Assert.NotNull(cred); Assert.IsInstanceOf(typeof(CertificateCredential), cred); CertificateCredential cert = (CertificateCredential)cred; Assert.AreEqual(apiUsername, cert.APIUsername); Assert.AreEqual("Y382QH72D4MQYJT3", cert.APIPassword); Assert.AreEqual("C:/certs/paypal.p12", cert.CertificateFile); Assert.AreEqual("11111111", cert.PrivateKeyPassword); Assert.AreEqual("APP-5XV204960S3290106", cert.ApplicationID); }
public DtlsClientSecurityContext( SecurityPackageType packageType, CertificateCredential clientCredential, string serverPrincipal, ClientSecurityContextAttribute contextAttributes, SecurityTargetDataRepresentation targetDataRep) { if (clientCredential == null) { clientCredential = new CertificateCredential(null); } this.packageType = packageType; this.serverPrincipalName = serverPrincipal; this.securityContextAttributes = contextAttributes; this.targetDataRepresentaion = targetDataRep; this.Context = new Sspi.DtlsClientSecurityContext(packageType, clientCredential, serverPrincipal, contextAttributes, targetDataRep) as IDtlsClientSecurityContext; }
/// <summary> /// Validates the Certificate Credentials /// </summary> /// <param name="apiCredentials"></param> private void Validate(CertificateCredential apiCredentials) { if (string.IsNullOrEmpty(apiCredentials.UserName)) { throw new InvalidCredentialException(BaseConstants.ErrorMessages.ErrorUserName); } if (string.IsNullOrEmpty(apiCredentials.Password)) { throw new InvalidCredentialException(BaseConstants.ErrorMessages.ErrorPassword); } if (string.IsNullOrEmpty(((CertificateCredential)apiCredentials).CertificateFile)) { throw new InvalidCredentialException(BaseConstants.ErrorMessages.ErrorCertificate); } if (string.IsNullOrEmpty(((CertificateCredential)apiCredentials).PrivateKeyPassword)) { throw new InvalidCredentialException(BaseConstants.ErrorMessages.ErrorPrivateKeyPassword); } }
private async Task <Credential> CreateCertCredential(CredentialRequestInfo info) { // Handle challenges for a secured resource by prompting for a client certificate. Esri.ArcGISRuntime.Security.Credential credential = null; try { // Create an X509 store for reading certificates for the current user. var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); // Open the store in read-only mode. store.Open(OpenFlags.ReadOnly); // Get a list of certificates that are currently valid. X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true); // Prompt the user to select a certificate using the built-in certificate selection UI. var selection = X509Certificate2UI.SelectFromCollection(certificates, "Select Certificate", "Select the certificate to use for authentication.", X509SelectionFlag.SingleSelection); // Make sure the user chose a certificate. if (selection.Count > 0) { // Create a new CertificateCredential using the chosen certificate. credential = new CertificateCredential(selection[0]) { ServiceUri = new Uri(_serverUrl) }; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } // Return the CertificateCredential for the secured portal. return(await Task.FromResult(credential)); }
/// <summary> /// Returns the Certificate Credential as HTTP headers /// </summary> /// <param name="credential"></param> /// <returns></returns> public Dictionary <string, string> GenerateHeaderStrategy(CertificateCredential credential) { Dictionary <string, string> headers = null; try { if (credential.ThirdPartyAuthorization is TokenAuthorization) { headers = ProcessTokenAuthorization(credential, (TokenAuthorization)credential.ThirdPartyAuthorization); } else { headers = new Dictionary <string, string>(); headers.Add(BaseConstants.PayPalSecurityUserIdHeader, credential.UserName); headers.Add(BaseConstants.PayPalSecurityPasswordHeader, credential.Password); } } catch (OAuthException oex) { throw oex; } return(headers); }
/// <summary> /// Returns the Certificate Credential as HTTP headers /// </summary> /// <param name="credential"></param> /// <returns></returns> public Dictionary <string, string> GenerateHeaderStrategy(CertificateCredential credential) { Dictionary <string, string> headers = null; try { if (credential.ThirdPartyAuthorization is TokenAuthorization) { headers = ProcessTokenAuthorization(credential, (TokenAuthorization)credential.ThirdPartyAuthorization); } else { headers = new Dictionary <string, string>(); headers.Add(BaseConstants.PAYPAL_SECURITY_USERID_HEADER, credential.UserName); headers.Add(BaseConstants.PAYPAL_SECURITY_PASSWORD_HEADER, credential.Password); } } catch (OAuthException ae) { throw ae; } return(headers); }
/// <summary> /// Appends SOAP Headers to payload /// if the credentials mandate soap headers /// </summary> /// <returns></returns> public string GetPayload() { if (payload == null) { payload = apiCallHandler.GetPayload(); string header = null; if (credential is SignatureCredential) { SignatureCredential signCredential = (SignatureCredential)credential; SignatureSOAPHeaderAuthStrategy signSoapHeaderAuthStrategy = new SignatureSOAPHeaderAuthStrategy(); signSoapHeaderAuthStrategy.ThirdPartyAuthorization = signCredential.ThirdPartyAuthorization; header = signSoapHeaderAuthStrategy.GenerateHeaderStrategy(signCredential); } else if (credential is CertificateCredential) { CertificateCredential certCredential = (CertificateCredential)credential; CertificateSOAPHeaderAuthStrategy certSoapHeaderAuthStrategy = new CertificateSOAPHeaderAuthStrategy(); certSoapHeaderAuthStrategy.ThirdPartyAuthorization = certCredential.ThirdPartyAuthorization; header = certSoapHeaderAuthStrategy.GenerateHeaderStrategy(certCredential); } payload = GetPayloadUsingSOAPHeader(payload, GetAttributeNamespace(), header); } return(payload); }
public static AuthenticationContainer FromCertificateCredential(CertificateCredential credential) { return(credential != null ? new AuthenticationContainer(credential.Certificate) : null); }
/// <summary> /// Process Token Authorization based on API format /// </summary> /// <param name="certCredential"></param> /// <param name="tokenAuthorize"></param> /// <returns></returns> protected abstract Dictionary <string, string> ProcessTokenAuthorization(CertificateCredential certCredential, TokenAuthorization tokenAuthorize);
/// <summary> /// Retrieves all ArcGISRuntime credentials stored in the isolated storage. /// </summary> public static IEnumerable<Credential> RetrieveAll() { var credentials = new List<Credential>(); foreach(var cachedCredential in GetCachedCredentials()) { Credential credential = null; string userName = cachedCredential.UserName; string passwordValue = cachedCredential.Password; // value stored as password string serviceUrl = cachedCredential.Url; // Create the credential depending on the type if (passwordValue.StartsWith(PasswordPrefix)) { string password = passwordValue.Substring(PasswordPrefix.Length); credential = new ArcGISTokenCredential { ServiceUri = serviceUrl, UserName = userName, Password = password, Token = "dummy" }; // dummy to remove once the token will be refreshed pro actively } else if (passwordValue.StartsWith(OAuthRefreshTokenPrefix)) { string refreshToken = passwordValue.Substring(OAuthRefreshTokenPrefix.Length); credential = new OAuthTokenCredential { ServiceUri = serviceUrl, UserName = userName, OAuthRefreshToken = refreshToken, Token = "dummy" }; } else if (passwordValue.StartsWith(OAuthAccessTokenPrefix)) { string token = passwordValue.Substring(OAuthAccessTokenPrefix.Length); credential = new OAuthTokenCredential { ServiceUri = serviceUrl, UserName = userName, Token = token, }; } else if (passwordValue.StartsWith(NetworkCredentialPasswordPrefix)) { string password = passwordValue.Substring(NetworkCredentialPasswordPrefix.Length); credential = new ArcGISNetworkCredential { ServiceUri = serviceUrl, Credentials = new NetworkCredential(userName, password) }; } else if (passwordValue.StartsWith(CertificateCredentialPrefix)) { string serial = passwordValue.Substring(CertificateCredentialPrefix.Length); var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); X509Certificate2Collection certificates; try { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); // Find certificate by serial number certificates = store.Certificates.Find(X509FindType.FindBySerialNumber, serial, true); } catch (Exception) { certificates = null; } finally { store.Close(); } if (certificates != null && certificates.Count > 0) credential = new CertificateCredential(certificates[0]) { ServiceUri = serviceUrl }; } if (credential != null) { credentials.Add(credential); } } return credentials; }
public void GenerateHeaderStrategyThirdPartyAuthorization() { certCredential = new CertificateCredential("testusername", "testpassword", "sdk-cert.p12", "KJAERUGBLVF6Y"); certSOAPHeaderAuthStrategy = new CertificateSOAPHeaderAuthStrategy(); subAuthorization = new SubjectAuthorization("testsubject"); certSOAPHeaderAuthStrategy.ThirdPartyAuthorization = subAuthorization; certCredential.ThirdPartyAuthorization = subAuthorization; string payload = certSOAPHeaderAuthStrategy.GenerateHeaderStrategy(certCredential); XmlDocument xmlDoc = GetXmlDocument(payload); XmlNodeList xmlNodeListUsername = xmlDoc.GetElementsByTagName("Username"); Assert.IsTrue(xmlNodeListUsername.Count > 0); Assert.AreEqual("testusername", xmlNodeListUsername[0].InnerXml); XmlNodeList xmlNodeListPassword = xmlDoc.GetElementsByTagName("Password"); Assert.IsTrue(xmlNodeListPassword.Count > 0); Assert.AreEqual("testpassword", xmlNodeListPassword[0].InnerXml); XmlNodeList xmlNodeListSubject = xmlDoc.GetElementsByTagName("Subject"); Assert.IsTrue(xmlNodeListSubject.Count > 0); Assert.AreEqual("testsubject", xmlNodeListSubject[0].InnerXml); }
public void CertificateCredentialArgumentException() { certCredential = new CertificateCredential(null, null, null, null); }
public void GenerateHeaderStrategyWithToken() { certHttpHeaderAuthStrategy = new CertificateHttpHeaderAuthStrategy(Constants.APIEndpointSOAP); TokenAuthorization toknAuthorization = new TokenAuthorization(Constants.AccessToken, Constants.TokenSecret); CertificateCredential certCredential = new CertificateCredential("testusername", "testpassword", "sdk-cert.p12", "KJAERUGBLVF6Y", toknAuthorization); Dictionary<string, string> header = certHttpHeaderAuthStrategy.GenerateHeaderStrategy(certCredential); string authHeader = header[BaseConstants.PayPalAuthorizationMerchantHeader]; string[] headers = authHeader.Split(','); Assert.AreEqual("token=" + Constants.AccessToken, headers[0]); }
public CertificateCredentialTest() { certCredential = new CertificateCredential("platfo_1255077030_biz_api1.gmail.com", "1255077037", "sdk-cert.p12", "KJAERUGBLVF6Y"); }
private Task<Credential> CreateCertificateCredentialAsync(CredentialRequestInfo credentialRequestInfo) { var tcs = new TaskCompletionSource<Credential>(); var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); X509Certificate2Collection certificates; try { const string clientAuthOid = "1.3.6.1.5.5.7.3.2"; // Client Authentication OID store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); // Find Client Authentication certificate certificates = store.Certificates.Find(X509FindType.FindByApplicationPolicy, clientAuthOid, true); } catch (Exception) { certificates = null; } finally { store.Close(); } string url = credentialRequestInfo.ServiceUri; ServerInfo serverInfo = IdentityManager.Current.FindServerInfo(url); if (certificates != null && certificates.Count >= 1) { // Let the user select/validate the certificate string resourceName = GetResourceName(url); string server = serverInfo == null ? Regex.Match(url, "http.?//[^/]*").ToString() : serverInfo.ServerUri; string message = resourceName == null ? string.Format("certificate required to access to {0}", server) : string.Format("certificate required to access {0} on {1}", resourceName, server); certificates = X509Certificate2UI.SelectFromCollection(certificates, null, message, X509SelectionFlag.SingleSelection); } if (certificates != null && certificates.Count > 0) { var credential = new CertificateCredential(certificates[0]) { ServiceUri = serverInfo == null ? url : serverInfo.ServerUri }; if (AllowSaveCredentials) CredentialManager.AddCredential(credential); tcs.TrySetResult(credential); } else { // Note : Error type is not that important since the error returned to the user is the initial HTTP error (Authorization Error) tcs.TrySetException(new System.Security.Authentication.AuthenticationException()); } return tcs.Task; }