public ActionResult Twitter(string method)
        {
            try
            {
                if (Session["Twitter:AccessToken"] == null)
                {
                    throw new Exception(Test.Resources.Strings.SessionIsDead);
                }

                string url = "https://api.twitter.com/1.1/followers/ids.json";

                if (method == "user_timeline")
                {
                    url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
                }

                var auth = new OAuthAuthorization();
                auth["oauth_consumer_key"]     = ConfigurationManager.AppSettings["oauth:twitter:id"];
                auth["oauth_signature_method"] = SignatureMethods.HMACSHA1;
                auth["oauth_nonce"]            = OAuthUtility.GetRandomKey();
                auth["oauth_timestamp"]        = OAuthUtility.GetTimeStamp();
                auth["oauth_token_secret"]     = Session["Twitter:TokenSecret"].ToString();
                auth["oauth_token"]            = Session["Twitter:AccessToken"].ToString();
                auth["oauth_version"]          = "1.0";
                auth.SetSignature("GET", new Uri(url), ConfigurationManager.AppSettings["oauth:twitter:key"], Session["Twitter:TokenSecret"].ToString(), null);

                var result = OAuthUtility.ExecuteRequest("GET", url, authorization: auth.ToString());

                return(Content(Regex.Unescape(result.ToString()), "text/plain"));
            }
            catch (Exception ex)
            {
                return(Content(ex.ToString(), "text/plain"));
            }
        }
        public async Task WhenExistingAuthIsOk_TryLoadExistingAuthorizationAsyncReturnsAuthorization()
        {
            var tokenResponse = new TokenResponse()
            {
                RefreshToken = "rt",
                Scope        = "email one two"
            };

            var adapter = new Mock <IAuthAdapter>();

            adapter.Setup(a => a.GetStoredRefreshTokenAsync(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(tokenResponse));
            adapter.Setup(a => a.IsRefreshTokenValid(tokenResponse))
            .Returns(true);
            adapter.SetupGet(a => a.Scopes)
            .Returns(new[] { "one", "two", "email" });

            var authz = await OAuthAuthorization.TryLoadExistingAuthorizationAsync(
                adapter.Object,
                CancellationToken.None);

            Assert.IsNotNull(authz);

            adapter.Verify(a => a.AuthorizeUsingRefreshToken(tokenResponse), Times.Once);
            adapter.Verify(a => a.QueryUserInfoAsync(
                               It.IsAny <ICredential>(),
                               It.IsAny <CancellationToken>()), Times.Once);
        }
Beispiel #3
0
        public void Signature_Common()
        {
            string httpMethod         = "GET";
            string url                = "https://localhost/test";
            NameValueCollection param = null;

            var auth = new OAuthAuthorization();

            auth.ConsumerKey     = "12345";
            auth.ConsumerSecret  = "1234567890";
            auth.TokenSecret     = "abc";
            auth.Token           = "xyz";
            auth.Nonce           = "000000";
            auth.SignatureMethod = "HMAC-SHA1";
            auth.Timestamp       = "1111111111";
            auth.Version         = "1.0";

            string b = OAuthAuthorization.GetSignatureBaseString(httpMethod, url, param, auth);

            var singn = new OAuthSignature
                        (
                auth.SignatureMethod,
                String.Format("{0}&{1}", auth.ConsumerSecret, auth.TokenSecret),
                OAuthAuthorization.GetSignatureBaseString(httpMethod, url, param, auth)
                        ).ToString();

            if (singn != "vYE8cEP5ynznQRDqTxx307kc6rY=")
            {
                Assert.Fail();
            }
            else
            {
                Console.WriteLine("OK");
            }
        }
        public async Task WhenExistingAuthLacksScopes_TryLoadExistingAuthorizationAsyncReturnsNullAndExistingAuthzIsDeleted()
        {
            var tokenResponse = new TokenResponse()
            {
                RefreshToken = "rt",
                Scope        = "one two"
            };

            var adapter = new Mock <IAuthAdapter>();

            adapter.Setup(a => a.GetStoredRefreshTokenAsync(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(tokenResponse));
            adapter.Setup(a => a.IsRefreshTokenValid(tokenResponse))
            .Returns(true);
            adapter.SetupGet(a => a.Scopes)
            .Returns(new[] { "one", "two", "email" });

            var authz = await OAuthAuthorization.TryLoadExistingAuthorizationAsync(
                adapter.Object,
                CancellationToken.None);

            Assert.IsNull(authz);

            adapter.Verify(a => a.DeleteStoredRefreshToken(), Times.Once);
        }
        public void BodyHash()
        {
            NameValueCollection param = null;
            string httpMethod         = "GET";
            string url = "https://localhost/test";

            var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();

            var auth = new OAuthAuthorization();

            auth.ConsumerKey        = "123123123";
            auth.ConsumerSecret     = "111111111111";
            auth.SignatureMethod    = "HMAC-SHA1";
            auth.Nonce              = "10098421";
            auth.Timestamp          = "1423300052";
            auth.Version            = "1.0";
            auth["oauth_body_hash"] = Convert.ToBase64String(sha1.ComputeHash(new byte[] { }));

            string b = OAuthAuthorization.GetSignatureBaseString(httpMethod, url, param, auth);

            var singn = new OAuthSignature
                        (
                auth.SignatureMethod,
                String.Format("{0}&{1}", auth.ConsumerSecret, auth.TokenSecret),
                OAuthAuthorization.GetSignatureBaseString(httpMethod, url, param, auth)
                        ).ToString();

            Assert.Equal("0dMQJB8HJSDse2/P4C0icvIbHfU=", singn);
        }
Beispiel #6
0
        /// <summary>
        /// Wraps an API request - if the request is unauthorized it will refresh the Auth token and re-issue the request
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        /// <returns></returns>
        private async Task <IApiResponse> WrapApiRequestAsync(OAuthAuthorization authResponse, Func <OAuthAuthorization, Task <IApiResponse> > func)
        {
            try
            {
                return(await func(authResponse));
            }
            catch (DigikeyUnauthorizedException ex)
            {
                // get refresh token, retry
                _oAuth2Service.ClientSettings.RefreshToken = ex.Authorization.RefreshToken;
                var token = await _oAuth2Service.RefreshTokenAsync();

                var refreshTokenResponse = new OAuthAuthorization(nameof(DigikeyApi), _oAuth2Service.ClientSettings.ClientId, _httpContextAccessor.HttpContext.Request.Headers["Referer"].ToString())
                {
                    AccessToken           = token.AccessToken,
                    RefreshToken          = token.RefreshToken,
                    CreatedUtc            = DateTime.UtcNow,
                    ExpiresUtc            = DateTime.UtcNow.Add(TimeSpan.FromSeconds(token.ExpiresIn)),
                    AuthorizationReceived = true,
                };
                var contextKey = $"{nameof(DigikeyApi)}-{_httpContextAccessor.HttpContext.User.Identity.Name}";
                ServerContext.Set(contextKey, refreshTokenResponse);
                if (refreshTokenResponse.IsAuthorized)
                {
                    // save the credential
                    await _credentialService.SaveOAuthCredentialAsync(new Common.Models.OAuthCredential
                    {
                        Provider       = contextKey,
                        AccessToken    = refreshTokenResponse.AccessToken,
                        RefreshToken   = refreshTokenResponse.RefreshToken,
                        DateCreatedUtc = refreshTokenResponse.CreatedUtc,
                        DateExpiresUtc = refreshTokenResponse.ExpiresUtc,
                    });

                    try
                    {
                        // call the API again using the refresh token
                        return(await func(refreshTokenResponse));
                    }
                    catch (DigikeyUnauthorizedException)
                    {
                        // refresh token failed, restart access token retrieval process
                        await ForgetAuthenticationTokens();

                        var freshResponse = await AuthorizeAsync();

                        if (freshResponse.MustAuthorize)
                        {
                            return(ApiResponse.Create(true, freshResponse.AuthorizationUrl, $"User must authorize", nameof(DigikeyApi)));
                        }
                        // call the API again
                        return(await func(freshResponse));
                    }
                }
                throw new UnauthorizedAccessException("Unable to authenticate with Digikey!");
            }
        }
        private static void AppendOAuth2(OpenApiSecurityScheme scheme, OAuthAuthorization oAuth2)
        {
            Debug.Assert(scheme != null);
            Debug.Assert(oAuth2 != null);

            scheme.Flows = new OpenApiOAuthFlows();
            OpenApiOAuthFlow flow = null;

            switch (oAuth2.OAuth2Type)
            {
            case OAuth2Type.AuthCode:     // AuthCode
                OAuth2AuthCode authCode = (OAuth2AuthCode)oAuth2;
                flow = new OpenApiOAuthFlow
                {
                    AuthorizationUrl = new Uri(authCode.AuthorizationUrl),
                    TokenUrl         = new Uri(authCode.TokenUrl)
                };
                scheme.Flows.AuthorizationCode = flow;
                break;

            case OAuth2Type.Pasword:     // Password
                OAuth2Password password = (OAuth2Password)oAuth2;
                flow = new OpenApiOAuthFlow
                {
                    TokenUrl = new Uri(password.TokenUrl)
                };
                scheme.Flows.Password = flow;
                break;

            case OAuth2Type.Implicit:     // Implicit
                OAuth2Implicit @implicit = (OAuth2Implicit)oAuth2;
                flow = new OpenApiOAuthFlow
                {
                    AuthorizationUrl = new Uri(@implicit.AuthorizationUrl)
                };
                scheme.Flows.Implicit = flow;
                break;

            case OAuth2Type.ClientCredentials:     // ClientCredentials
                OAuth2ClientCredentials credentials = (OAuth2ClientCredentials)oAuth2;
                flow = new OpenApiOAuthFlow
                {
                    TokenUrl = new Uri(credentials.TokenUrl)
                };
                scheme.Flows.ClientCredentials = flow;
                break;
            }

            Debug.Assert(flow != null);
            flow.RefreshUrl = new Uri(oAuth2.RefreshUrl);

            if (oAuth2.Scopes != null)
            {
                flow.Scopes = oAuth2.Scopes.ToDictionary(s => s.Scope, s => s.Description);
            }
        }
Beispiel #8
0
        private HttpRequestMessage CreateRequest(OAuthAuthorization authResponse, HttpMethod method, Uri uri)
        {
            var message = new HttpRequestMessage(method, uri);

            message.Headers.Add("X-DIGIKEY-Client-Id", authResponse.ClientId);
            message.Headers.Add("Authorization", $"Bearer {authResponse.AccessToken}");
            message.Headers.Add("X-DIGIKEY-Locale-Site", "CA");
            message.Headers.Add("X-DIGIKEY-Locale-Language", "en");
            message.Headers.Add("X-DIGIKEY-Locale-Currency", "CAD");
            return(message);
        }
Beispiel #9
0
        private OAuthAuthorization GetAuth()
        {
            var auth = new OAuthAuthorization();

            auth.ConsumerKey     = this.ConsumerKey;
            auth.ConsumerSecret  = this.ConsumerSecret;
            auth.SignatureMethod = SignatureMethods.HMACSHA1;
            auth.Token           = Properties.Settings.Default.AccessToken;
            auth.TokenSecret     = Properties.Settings.Default.TokenSecret;
            return(auth);
        }
Beispiel #10
0
 public static IAuthorization getAuth(AuthType aType)
 {
     if (aType == AuthType.OAuth)
     {
         currentAuth = OAuthAuthorization.getInstance();
         return(currentAuth);
     }
     else
     {
         return(null);
     }
 }
        public async Task WhenNoExistingAuthPresent_TryLoadExistingAuthorizationAsyncReturnsNull()
        {
            var adapter = new Mock <IAuthAdapter>();

            adapter.Setup(a => a.GetStoredRefreshTokenAsync(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <TokenResponse>(null));

            var authz = await OAuthAuthorization.TryLoadExistingAuthorizationAsync(
                adapter.Object,
                CancellationToken.None);

            Assert.IsNull(authz);
        }
Beispiel #12
0
        private async Task <OAuthAuthorization> AuthorizeAsync()
        {
            var contextKey = $"{nameof(DigikeyApi)}-{_httpContextAccessor.HttpContext.User.Identity.Name}";
            // check if we have an in-memory auth credential
            var getAuth = ServerContext.Get <OAuthAuthorization>(contextKey);

            if (getAuth != null && getAuth.IsAuthorized)
            {
                return(getAuth);
            }

            // check if we have a saved to disk auth credential
            OAuthAuthorization authRequest;
            var credential = await _credentialService.GetOAuthCredentialAsync(contextKey);

            if (credential != null)
            {
                // reuse a saved oAuth credential
                authRequest = new OAuthAuthorization(nameof(DigikeyApi), _oAuth2Service.ClientSettings.ClientId, _httpContextAccessor.HttpContext.Request.Headers["Referer"].ToString())
                {
                    AccessToken           = credential.AccessToken,
                    RefreshToken          = credential.RefreshToken,
                    CreatedUtc            = credential.DateCreatedUtc,
                    ExpiresUtc            = credential.DateExpiresUtc,
                    AuthorizationReceived = true,
                };
                // also store it in memory
                ServerContext.Set(contextKey, authRequest);
                return(authRequest);
            }

            // user must authorize
            // request a token if we don't already have one
            var scopes  = "";
            var authUrl = _oAuth2Service.GenerateAuthUrl(scopes);

            // OpenBrowser(authUrl);
            authRequest = new OAuthAuthorization(nameof(DigikeyApi), _oAuth2Service.ClientSettings.ClientId, _httpContextAccessor.HttpContext.Request.Headers["Referer"].ToString());
            ServerContext.Set(contextKey, authRequest);

            return(new OAuthAuthorization(nameof(DigikeyApi), true, authUrl));
        }
Beispiel #13
0
        public ModifyResult UpdateOAuthUserAuthorization(Stream input, int id)
        {
            /*StreamReader reader = new StreamReader(input);
             * String content = reader.ReadToEnd();*/

            XmlSerializer      xmlSerializer = new XmlSerializer(typeof(OAuthAuthorization));
            OAuthAuthorization auth          = (OAuthAuthorization)xmlSerializer.Deserialize(input);

            // Create the mapper
            Arena.Custom.HDC.WebService.Contracts.OAuthAuthorizationMapper mapper =
                new Arena.Custom.HDC.WebService.Contracts.OAuthAuthorizationMapper();
            if (auth.AuthorizationId > 0)
            {
                return(mapper.Update(auth));
            }
            else
            {
                return(mapper.Create(auth));
            }
        }
Beispiel #14
0
        public ModifyResult UpdateOAuthUserAuthorization(String clientApiKey, OAuthAuthorization auth)
        {
            Arena.Custom.SECC.OAuth.Client client = new Arena.Custom.SECC.OAuth.Client(new Guid(clientApiKey));
            if (auth.ClientId != client.ClientId)
            {
                throw new ResourceNotFoundException("Client API Key mismatch.");
            }

            // Create the mapper
            Arena.Custom.HDC.WebService.Contracts.OAuthAuthorizationMapper mapper =
                new Arena.Custom.HDC.WebService.Contracts.OAuthAuthorizationMapper();
            if (auth.AuthorizationId > 0)
            {
                return(mapper.Update(auth));
            }
            else
            {
                return(mapper.Create(auth));
            }
        }
Beispiel #15
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Assigning controls
            Button   button   = FindViewById <Button> (Resource.Id.myButton);
            EditText username = FindViewById <EditText> (Resource.Id.editText1);
            EditText password = FindViewById <EditText> (Resource.Id.editText2);

            // Twitter configuration part
            ConfigurationBuilder TwitterConfig = new ConfigurationBuilder();

            TwitterConfig.SetOAuthConsumerKey("_replace_wit_your_app_consumer_key_");
            TwitterConfig.SetOAuthConsumerSecret("_replace_wit_your_app_consumer_secret_");
            IConfiguration twiConfigInterface = TwitterConfig.Build();

            TwitterFactory factory = new TwitterFactory(twiConfigInterface);

            OAuthAuthorization oath = new OAuthAuthorization(twiConfigInterface);

            AccessToken ascTkn  = oath.GetOAuthAccessToken(username.Text, password.Text);
            ITwitter    twitter = factory.GetInstance(ascTkn);

            button.Click += delegate {
                ThreadPool.QueueUserWorkItem(state =>
                {
                    try
                    {
                        twitter.UpdateStatus("Hello world, Xamarin is exciting.. boom..");
                    }
                    catch (Exception ed)
                    {
                        Console.WriteLine(ed.Message);
                    }
                }
                                             );
            };
        }
Beispiel #16
0
        public ActionResult Twitter(string method)
        {
            try
            {
                if (Session["Twitter:AccessToken"] == null)
                {
                    throw new Exception(DemoOAuth.Strings.SessionIsDead);
                }

                var token = (OAuthAccessToken)Session["Twitter:AccessToken"];

                string url = "https://api.twitter.com/1.1/followers/ids.json";

                if (method == "user_timeline")
                {
                    url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
                }

                var auth = new OAuthAuthorization();
                auth.ConsumerKey     = ConfigurationManager.AppSettings["oauth:twitter:id"];
                auth.ConsumerSecret  = ConfigurationManager.AppSettings["oauth:twitter:key"];
                auth.TokenSecret     = token.TokenSecret;
                auth.SignatureMethod = SignatureMethods.HMACSHA1;
                auth.Nonce           = OAuthUtility.GetRandomKey();
                auth.Timestamp       = OAuthUtility.GetTimeStamp();
                auth.Token           = token.Value;
                auth.Version         = "1.0";

                var result = OAuthUtility.ExecuteRequest("GET", url, authorization: auth);

                return(Content(result.ToString(), "text/plain"));
            }
            catch (Exception ex)
            {
                return(Content(ex.ToString(), "text/plain"));
            }
        }
Beispiel #17
0
        public static IAuthorization Authorize(
            Control parent,
            ClientSecrets clientSecrets,
            string[] scopes,
            IDataStore dataStore)
        {
            // N.B. Do not dispose the adapter (and embedded GoogleAuthorizationCodeFlow)
            // as it might be needed for token refreshes later.
            var oauthAdapter = new GoogleAuthAdapter(
                new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = clientSecrets,
                Scopes        = scopes,
                DataStore     = dataStore
            },
                Resources.AuthorizationSuccessful);

            Exception caughtException = null;

            using (var dialog = new AuthorizeDialog())
            {
                Task.Run(async() =>
                {
                    try
                    {
                        // Try to authorize using OAuth.
                        dialog.authorization = await OAuthAuthorization.TryLoadExistingAuthorizationAsync(
                            oauthAdapter,
                            CancellationToken.None)
                                               .ConfigureAwait(true);

                        if (dialog.authorization != null)
                        {
                            // We have existing credentials, there is no need to even
                            // show the "Sign In" button.
                            parent.BeginInvoke((Action)(() => dialog.Close()));
                        }
                        else
                        {
                            // No valid credentials present, request user to authroize
                            // by showing the "Sign In" button.
                            parent.BeginInvoke((Action)(() => dialog.ToggleSignInButton()));
                        }
                    }
                    catch (Exception)
                    {
                        // Something went wrong trying to load existing credentials.
                        parent.BeginInvoke((Action)(() => dialog.ToggleSignInButton()));
                    }
                });

                dialog.signInButton.Click += async(sender, args) =>
                {
                    // Switch to showing spinner so that a user cannot click twice.
                    dialog.ToggleSignInButton();

                    try
                    {
                        dialog.authorization = await OAuthAuthorization.CreateAuthorizationAsync(
                            oauthAdapter,
                            CancellationToken.None)
                                               .ConfigureAwait(true);
                    }
                    catch (Exception e)
                    {
                        caughtException = e;
                    }

                    dialog.Close();
                };

                dialog.ShowDialog(parent);

#pragma warning disable CA1508 // Avoid dead conditional code
                if (caughtException != null)
                {
                    throw caughtException;
                }
                else
                {
                    return(dialog.authorization);
                }
#pragma warning restore CA1508 // Avoid dead conditional code
            }
        }
Beispiel #18
0
 public DigikeyUnauthorizedException(OAuthAuthorization authorization)
 {
     Authorization = authorization;
 }
 protected override void OnValidSuccess(AuthorizationContext filterContext, ServerAccessGrant accessGrant)
 {
     OAuthAuthorization.AppendRequestData(filterContext.RequestContext, "userId", accessGrant.UserId);
     OAuthAuthorization.AppendRequestData(filterContext.RequestContext, "appId", accessGrant.ClientId);
 }