Exemple #1
0
        public async Task <OAuth2AccessToken> RequestTokenWithWithUserNameAsync(OAuth2Credential credential, string userName, string password, string resourceId, string scope)
        {
            if (credential == null)
            {
                throw new ArgumentNullException("credential");
            }

            Dictionary <string, string> fields = new Dictionary <string, string>();

            fields["grant_type"]    = "password";
            fields["client_id"]     = credential.ClientId;
            fields["client_secret"] = credential.ClientSecret;
            fields["username"]      = userName;
            fields["password"]      = password;

            if (!String.IsNullOrEmpty(credential.RedirectUrl))
            {
                fields["redirect_uri"] = credential.RedirectUrl;
            }

            if (!String.IsNullOrEmpty(resourceId))
            {
                fields["resource"] = resourceId;
            }

            if (!String.IsNullOrEmpty(scope))
            {
                fields["scope"] = scope;
            }

            var url = new UriBuilder(credential.AuthorityUrl);

            url.Path += credential.TokenEndpoint;
            return(await RequestTokenAsync(url.Uri, fields));
        }
Exemple #2
0
        public void multiple_credentials_via_user_supplied_credential_cache()
        {
            const string secretsPath     = @"ExamplesTests\client_secrets.json";
            const string credentialsPath = @"ExamplesTests\stored_credentials.json";

            var simpleCred = new NetworkCredential(_username, _password);

            var windowsIntegratedCredential = CredentialCache.DefaultNetworkCredentials;

            var oAuth2Credential = new OAuth2Credential(
                "apiv1",
                new Storage.JsonFileStorage(
                    secretsPath,
                    credentialsPath),
                null
                );

            var cache = new CredentialCache();
            var uri   = new Uri(_prefix);

            cache.Add(uri, "Basic", simpleCred);
            cache.Add(uri, "Bearer", oAuth2Credential);
            // Suppose for some weird reason you just wanted to support NTLM:
            cache.Add(uri, "NTLM", windowsIntegratedCredential);

            var connector = new VersionOneAPIConnector(_prefix, cache);

            using (connector.GetData(Path));
        }
Exemple #3
0
        public async Task <OAuth2AccessToken> RequestTokenWithWithSiteTokenAsync(OAuth2Credential credential, X509Certificate2 certificate, string accessToken, string resourceId, string scope)
        {
            if (credential == null)
            {
                throw new ArgumentNullException("credential");
            }

            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }

            Dictionary <string, string> fields = new Dictionary <string, string>();

            var clientId = certificate.GetRawCertData();

            var random = new RNGCryptoServiceProvider();
            var nonce  = new byte[32];

            random.GetBytes(nonce);

            var dataToSign = Utils.Append(new UTF8Encoding(false).GetBytes(accessToken), nonce);
            var signature  = RsaUtils.RsaPkcs15Sha1_Sign(new ArraySegment <byte>(dataToSign), certificate);

            fields["grant_type"]    = "urn:opcfoundation.org:oauth2:site_token";
            fields["client_id"]     = Convert.ToBase64String(clientId);
            fields["client_secret"] = Convert.ToBase64String(signature);
            fields["nonce"]         = Convert.ToBase64String(nonce);
            fields["access_token"]  = accessToken;

            if (!String.IsNullOrEmpty(credential.RedirectUrl))
            {
                fields["redirect_uri"] = credential.RedirectUrl;
            }

            if (!String.IsNullOrEmpty(resourceId))
            {
                fields["resource"] = resourceId;
            }

            if (!String.IsNullOrEmpty(scope))
            {
                fields["scope"] = scope;
            }

            var url = new UriBuilder(credential.AuthorityUrl);

            url.Path += credential.TokenEndpoint;
            return(await RequestTokenAsync(url.Uri, fields));
        }
        public void GetAuthorizationCodeRequestUrl_CheckInvalidParams_Passed()
        {
            OAuth2Credential           credential = null;
            OAuth2TokenRequestSettings trSettings = null;
            var oauth2 = new OAuth2Utility(new DummyNetUtility());

            var argNullEx = Assert.Throws <ArgumentNullException>(() => oauth2.GetAuthorizationCodeRequestUrl(credential, trSettings));

            Assert.Equal("credential", argNullEx.ParamName);

            credential = new TestCredential();
            argNullEx  = Assert.Throws <ArgumentNullException>(() => oauth2.GetAuthorizationCodeRequestUrl(credential, trSettings));
            Assert.Equal("requestSettings", argNullEx.ParamName);

            trSettings = new OAuth2TokenRequestSettings();
            var argEx = Assert.Throws <ArgumentException>(() => oauth2.GetAuthorizationCodeRequestUrl(credential, trSettings));

            Assert.True(argEx.Message.Contains("RedirectUri must match one of the values in credential.RedirectUrls"));
        }
        private void ObtainValidAccessToken(TestConfig testConfig)
        {
            lock (_lock)
            {
                if (!IsAccessTokenExpired(testConfig))
                {
                    return;
                }
                var              oauth2Util = new OAuth2Utility(GetNetUtility());
                string           fullPath   = testConfig.GetFilePath(testConfig.Oauth2.CredentialJsonPath);
                OAuth2Credential credential = InstalledAppCredential.ReadFromFile(fullPath);
                if (credential.ProjectId == null)
                {
                    credential = WebAppCredential.ReadFromFile(fullPath);
                }
                var tokenInfo = oauth2Util.GetTokenInfoAsync(credential, testConfig.Oauth2.RefreshToken).Result;

                testConfig.Oauth2.AccessToken = tokenInfo.AccessToken;
                testConfig.Oauth2.ExpiresIn   = tokenInfo.ExpiresIn;
                testConfig.Oauth2.IssuedTime  = tokenInfo.IssuedTime.ToUniversalTime().ToString("s", System.Globalization.CultureInfo.InvariantCulture) + "Z";
                testConfig.Save();
            }
        }
Exemple #6
0
        public OAuth2AccessToken ShowDialog(OAuth2Credential credential)
        {
            if (credential == null)
            {
                throw new ArgumentNullException("settings");
            }

            m_credential = credential;
            m_client     = new OAuth2Client();

            var url = new UriBuilder(m_credential.AuthorityUrl);

            url.Path += m_credential.AuthorizationEndpoint;
            url.Query = String.Format("response_type=code&client_id={0}&redirect_uri={1}", Uri.EscapeUriString(m_credential.ClientId), Uri.EscapeUriString(m_credential.RedirectUrl));

            Browser.Navigate(url.ToString());

            if (ShowDialog() != DialogResult.OK)
            {
                return(null);
            }

            return(m_token);
        }
Exemple #7
0
        public static async Task <UserIdentity> GetIdentityToken(ApplicationConfiguration configuration, string endpointUrl)
        {
            // get an endpoint to use.
            var endpoint = ClientUtils.SelectEndpoint(endpointUrl, true);

            // find user token policy that supports JWTs.
            JwtEndpointParameters parameters = null;

            foreach (var policy in endpoint.UserIdentityTokens)
            {
                if (policy.IssuedTokenType == "http://opcfoundation.org/UA/UserTokenPolicy#JWT")
                {
                    parameters = new JwtEndpointParameters();
                    parameters.FromJson(policy.IssuerEndpointUrl);
                    break;
                }
            }

            if (parameters == null)
            {
                throw new ServiceResultException(StatusCodes.BadConfigurationError, "No JWT UserTokenPolicy specified for the selected GDS.");
            }

            // set the default resource.
            if (String.IsNullOrEmpty(parameters.ResourceId))
            {
                parameters.ResourceId = endpoint.Server.ApplicationUri;
            }

            // get the authorization server that the GDS actually uses.
            var gdsCredentials = OAuth2CredentialCollection.FindByAuthorityUrl(configuration, parameters.AuthorityUrl);

            // create default credentials from the server endpoint.
            if (gdsCredentials == null)
            {
                gdsCredentials = new OAuth2Credential();
            }

            // override with settings provided by server.
            gdsCredentials.AuthorityUrl  = parameters.AuthorityUrl;
            gdsCredentials.GrantType     = parameters.GrantType;
            gdsCredentials.TokenEndpoint = parameters.TokenEndpoint;

            JwtSecurityToken jwt = null;

            // need to get credentials from an external authority.
            if (gdsCredentials != null && gdsCredentials.GrantType == "site_token")
            {
                // need to find an OAuth2 server that can supply credentials.
                var azureCredentials = OAuth2CredentialCollection.FindByServerUri(configuration, parameters.ResourceId);

                if (azureCredentials == null)
                {
                    throw new ServiceResultException(StatusCodes.BadConfigurationError, "No OAuth2 configuration specified for the selected GDS.");
                }

                // prompt user to provide credentials.
                var azureToken = new OAuth2CredentialsDialog().ShowDialog(azureCredentials);

                if (azureToken == null)
                {
                    return(null);
                }

                jwt = new JwtSecurityToken(azureToken.AccessToken);
                IssuedIdentityToken issuedToken = new IssuedIdentityToken();
                issuedToken.IssuedTokenType    = IssuedTokenType.JWT;
                issuedToken.DecryptedTokenData = new UTF8Encoding(false).GetBytes(jwt.RawData);
                var azureIdentity = new UserIdentity(issuedToken);

                // log in using site token.
                OAuth2Client client = new OAuth2Client()
                {
                    Configuration = configuration
                };
                var certificate = await client.Configuration.SecurityConfiguration.ApplicationCertificate.Find(true);

                var gdsAccessToken = await client.RequestTokenWithWithSiteTokenAsync(gdsCredentials, certificate, azureToken.AccessToken, parameters.ResourceId, "gdsadmin");

                JwtSecurityToken gdsToken = new JwtSecurityToken(gdsAccessToken.AccessToken);
                issuedToken = new IssuedIdentityToken();
                issuedToken.IssuedTokenType    = IssuedTokenType.JWT;
                issuedToken.DecryptedTokenData = new UTF8Encoding(false).GetBytes(gdsToken.RawData);
                return(new UserIdentity(issuedToken));
            }

            // attempt to log in directly
            else
            {
                string username = null;
                string password = null;

                // TBD - Prompt User to Provide.

                OAuth2Client client = new OAuth2Client()
                {
                    Configuration = configuration
                };
                var gdsAccessToken = await client.RequestTokenWithWithUserNameAsync(gdsCredentials, username, password, parameters.ResourceId, "gdsadmin");

                JwtSecurityToken    gdsToken    = new JwtSecurityToken(gdsAccessToken.AccessToken);
                IssuedIdentityToken issuedToken = new IssuedIdentityToken();
                issuedToken.IssuedTokenType    = IssuedTokenType.JWT;
                issuedToken.DecryptedTokenData = new UTF8Encoding(false).GetBytes(gdsToken.RawData);
                return(new UserIdentity(issuedToken));
            }
        }
Exemple #8
0
        public async Task <OAuth2AccessToken> RequestTokenWithAuthenticationCodeAsync(OAuth2Credential credential, string resourceId, string authenticationCode)
        {
            if (credential == null)
            {
                throw new ArgumentNullException("credential");
            }

            Dictionary <string, string> fields = new Dictionary <string, string>();

            fields["grant_type"] = "authorization_code";
            fields["code"]       = authenticationCode;
            fields["client_id"]  = credential.ClientId;

            if (!String.IsNullOrEmpty(credential.ClientSecret))
            {
                fields["client_secret"] = credential.ClientSecret;
            }

            if (!String.IsNullOrEmpty(credential.RedirectUrl))
            {
                fields["redirect_uri"] = credential.RedirectUrl;
            }

            if (!String.IsNullOrEmpty(resourceId))
            {
                fields["resource"] = resourceId;
            }

            var url = new UriBuilder(credential.AuthorityUrl);

            url.Path += credential.TokenEndpoint;
            return(await RequestTokenAsync(url.Uri, fields));
        }
        public void multiple_credentials_via_user_supplied_credential_cache()
        {
            const string secretsPath = @"ExamplesTests\client_secrets.json";
            const string credentialsPath = @"ExamplesTests\stored_credentials.json";

            var simpleCred = new NetworkCredential(_username, _password);

            var windowsIntegratedCredential = CredentialCache.DefaultNetworkCredentials;

            var oAuth2Credential = new OAuth2Credential(
                "apiv1",
                new Storage.JsonFileStorage(
                    secretsPath,
                    credentialsPath),
                null
                );

            var cache = new CredentialCache();
            var uri = new Uri(_prefix);
            cache.Add(uri, "Basic", simpleCred);
            cache.Add(uri, "Bearer", oAuth2Credential);
            // Suppose for some weird reason you just wanted to support NTLM:
            cache.Add(uri, "NTLM", windowsIntegratedCredential);

            var connector = new VersionOneAPIConnector(_prefix, cache);
            using (connector.GetData(Path)) ;
        }