Ejemplo n.º 1
0
        public static async Task <OAuth2AccessToken> ExchangeAuthCodeForAccessTokenAsync(string code)
        {
            HttpClient httpClient = new HttpClient();

            string postUrl = OAuth2Helper.FitbitOauthPostUrl;

            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("grant_type", "authorization_code"),
                new KeyValuePair <string, string>("client_id", ClientId),
                //new KeyValuePair<string, string>("client_secret", AppSecret),
                new KeyValuePair <string, string>("code", code),
                new KeyValuePair <string, string>("redirect_uri", RedirectUri)
            });


            string clientIdConcatSecret = OAuth2Helper.Base64Encode(ClientId + ":" + ClientSecret);

            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", clientIdConcatSecret);

            HttpResponseMessage response = await httpClient.PostAsync(postUrl, content);

            string responseString = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseString);
            OAuth2AccessToken accessToken = OAuth2Helper.ParseAccessTokenResponse(responseString);


            return(accessToken);
        }
Ejemplo n.º 2
0
        public override async Task AuthenticateAsync(CancellationToken cancellationToken)
        {
            var emailAccount = _db.EmailAccounts.FirstOrDefault(ea => ea.Email == Account.Email);

            if (emailAccount == null)
            {
                throw new InvalidOperationException($"No email account with address: {Account.Email}");
            }

            if (string.IsNullOrEmpty(emailAccount.AccessToken) || string.IsNullOrEmpty(emailAccount.RefreshToken))
            {
                throw new InvalidOperationException($"No token granted for email account: {emailAccount.Email}");
            }

            var refreshTokenRequest = new RefreshTokenRequest
            {
                ClientId     = emailAccount.Username,
                Secret       = emailAccount.Password,
                Tenant       = emailAccount.Email.Split('@')[1],
                RefreshToken = emailAccount.RefreshToken
            };

            refreshTokenRequest.Scopes.AddRange(M365Helper.EmailScopes);
            var token = await OAuth2Helper.RefreshTokenAsync(refreshTokenRequest);

            emailAccount.LastUpdateAccessToken = DateTime.UtcNow;
            _db.EmailAccounts.Update(emailAccount);
            await _db.SaveChangesAsync(cancellationToken);

            var auth = new SaslMechanismOAuth2(emailAccount.Email, token.AccessToken);
            await Client.AuthenticateAsync(auth, cancellationToken);
        }
Ejemplo n.º 3
0
        //Refresh AccessToken when expired.
        public static async Task <OAuth2AccessToken> RefreshTokenAsync(string expiredToken)
        {
            HttpClient httpClient = new HttpClient();

            string postUrl = OAuth2Helper.FitbitOauthPostUrl;

            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("grant_type", "refresh_token"),
                new KeyValuePair <string, string>("refresh_token", expiredToken),
            });


            string clientIdConcatSecret = OAuth2Helper.Base64Encode(ClientId + ":" + ClientSecret);

            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", clientIdConcatSecret);

            HttpResponseMessage response = await httpClient.PostAsync(postUrl, content);

            string responseString = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseString);
            OAuth2AccessToken accessToken = OAuth2Helper.ParseAccessTokenResponse(responseString);


            return(accessToken);
        }
Ejemplo n.º 4
0
        public void checkAuth(string url)
        {
            if (gotToken)
            {
                return;
            }

            if (url.Contains("?code="))
            {
                string[] splits = url.Split(new string[] { "?code=" }, StringSplitOptions.RemoveEmptyEntries);
                if (splits.Length == 2)
                {
                    this.Hide();
                    this.Close();
                    string code  = splits[1];
                    string token = OAuth2Helper.requestToken(GithubAPIInfo.client_id, GithubAPIInfo.client_secret, code);
                    if (token == null)
                    {
                        return;
                    }
                    gotToken = true;

                    GithubLoginInfo.OAuthToken = token;

                    MessageBox.Show(this.Owner as IWin32Window, "Successfully retrieved OAuth token.", "Github Authorization");
                }
            }
        }
Ejemplo n.º 5
0
        public void checkAuth(string url)
        {
            if (gotToken)
            {
                return;
            }

            if (url.Contains("?code="))
            {
                Uri uri         = new Uri(url);
                var queryParams = GetParams(uri.Query);
                if (queryParams.TryGetValue("code", out var code))
                {
                    this.Hide();
                    this.Close();
                    string token = OAuth2Helper.requestToken(GithubAPIInfo.client_id, GithubAPIInfo.client_secret, code);
                    if (token == null)
                    {
                        return;
                    }
                    gotToken = true;

                    GithubLoginInfo.OAuthToken = token;

                    MessageBox.Show(this.Owner as IWin32Window, "Successfully retrieved OAuth token.", "Github Authorization");
                }
            }
        }
Ejemplo n.º 6
0
        //[Authorize]
        public async Task <Dictionary <string, string> > TestHybridFlow(FormDataCollection formData)
        {
            // 変数
            string code = formData[OAuth2AndOIDCConst.code];

            // Tokenエンドポイントにアクセス
            Uri tokenEndpointUri = new Uri(
                ASPNETIdentityConfig.OAuth2AuthorizationServerEndpointsRootURI
                + ASPNETIdentityConfig.OAuth2BearerTokenEndpoint);

            // 結果を格納する変数。
            Dictionary <string, string> dic = null;

            //  client_Idから、client_secretを取得。
            string client_id     = OAuth2Helper.GetInstance().GetClientIdByName("TestClient");
            string client_secret = OAuth2Helper.GetInstance().GetClientSecret(client_id);

            // Hybridは、Implicitのredirect_uriを使用
            string redirect_uri
                = ASPNETIdentityConfig.OAuth2ClientEndpointsRootURI
                  + ASPNETIdentityConfig.OAuth2ImplicitGrantClient_Account;

            // Tokenエンドポイントにアクセス
            string response = await OAuth2Helper.GetInstance()
                              .GetAccessTokenByCodeAsync(tokenEndpointUri, client_id, client_secret, redirect_uri, code, "");

            dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(response);

            // UserInfoエンドポイントにアクセス
            dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(
                await OAuth2Helper.GetInstance().GetUserInfoAsync(dic[OAuth2AndOIDCConst.AccessToken]));

            return(dic);
        }
Ejemplo n.º 7
0
        public async Task AuthenticateAsync()
        {
            var oauthHelper = new OAuth2Helper(OAuthSettings);
            var startUri = new Uri(oauthHelper.GetAuthorizeUrl());
            var endUri = new Uri(OAuthSettings.CallbackUrl);

            var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);
            
            
            if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var result = webAuthenticationResult.ResponseData.ToString();
                var code = oauthHelper.GetCodeFromCallback(result);
                AuthorizationCode = code;
            }
            else if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                throw new Exception("HTTP Error returned by AuthenticateAsync.");
                //OutputToken("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
            }
            else
            {
                throw new Exception("Error returned by AuthenticateAsync.");
                //OutputToken("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
            }
        }
Ejemplo n.º 8
0
        public void checkAuth(string url)
        {
            if (gotToken)
            {
                return;
            }

            if (url.Contains("?code="))
            {
                Uri    uri  = new Uri(url);
                string code = HttpUtility.ParseQueryString(uri.Query).Get("code");
                if (!code.IsNullOrEmpty())
                {
                    this.Hide();
                    this.Close();
                    string token = OAuth2Helper.requestToken(GithubAPIInfo.client_id, GithubAPIInfo.client_secret, code);
                    if (token == null)
                    {
                        return;
                    }
                    gotToken = true;

                    GithubLoginInfo.OAuthToken = token;

                    MessageBox.Show(this.Owner as IWin32Window, "Successfully retrieved OAuth token.", "Github Authorization");
                }
            }
        }
Ejemplo n.º 9
0
        public void CheckAuth(string url)
        {
            if (_gotToken)
            {
                return;
            }

            if (url.Contains("?code="))
            {
                var uri         = new Uri(url);
                var queryParams = GetParams(uri.Query);
                if (queryParams.TryGetValue("code", out var code))
                {
                    Hide();
                    Close();
                    string token = OAuth2Helper.requestToken(GitHubApiInfo.client_id, GitHubApiInfo.client_secret, code);
                    if (token == null)
                    {
                        return;
                    }

                    _gotToken = true;

                    GitHubLoginInfo.OAuthToken = token;

                    MessageBox.Show(Owner, "Successfully retrieved OAuth token.", "GitHub Authorization");
                }
            }
        }
        public async Task <ActionResult> TestClientCredentialsFlow()
        {
            // Tokenエンドポイントにアクセス
            string aud = ASPNETIdentityConfig.OAuth2AuthorizationServerEndpointsRootURI
                         + ASPNETIdentityConfig.OAuth2BearerTokenEndpoint;

            // ClientNameから、client_id, client_secretを取得。
            string client_id     = "";
            string client_secret = "";

            if (User.Identity.IsAuthenticated)
            {
                // User Accountの場合、
                client_id     = OAuth2Helper.GetInstance().GetClientIdByName(User.Identity.Name);
                client_secret = OAuth2Helper.GetInstance().GetClientSecret(client_id);
            }
            else
            {
                // Client Accountの場合、
                client_id     = OAuth2Helper.GetInstance().GetClientIdByName("TestClient");
                client_secret = OAuth2Helper.GetInstance().GetClientSecret(client_id);
            }

            string response = await OAuth2Helper.GetInstance()
                              .ClientCredentialsGrantAsync(new Uri(
                                                               ASPNETIdentityConfig.OAuth2AuthorizationServerEndpointsRootURI
                                                               + ASPNETIdentityConfig.OAuth2BearerTokenEndpoint),
                                                           client_id, client_secret, ASPNETIdentityConst.StandardScopes);

            ViewBag.Response    = response;
            ViewBag.AccessToken = ((JObject)JsonConvert.DeserializeObject(response))[OAuth2AndOIDCConst.AccessToken];

            return(View("OAuth2ClientAuthenticationFlow"));
        }
Ejemplo n.º 11
0
        public void OAuth2Helper_Can_Deserialize_AccessToken()
        {
            string content = SampleDataHelper.GetContent("AccessToken.json");

            var result = OAuth2Helper.ParseAccessTokenResponse(content);

            Validate(result);
        }
        public async Task <ActionResult> SignInExternal(SaveTemporaryEmailAccountCommand command)
        {
            await _mediator.Send(command);

            var oAuth2AuthRequest = OAuth2Helper.CreateRequest(command.Email, command.UserId,
                                                               $"{Request.GetBaseUrl()}{Url.Action("LandingExternal")}", M365Helper.EmailScopes);

            return(View(oAuth2AuthRequest));
        }
Ejemplo n.º 13
0
        public ActionResult Login()
        {
            var authenticator = new OAuth2Helper(_appCredentials, ConfigurationManager.AppSettings["BaseUrl"] + "/band/callback");

            string[] scopes = new string[] { "profile" };

            string authUrl = authenticator.GenerateAuthUrl(scopes, null);

            return(Redirect(authUrl));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Part 1 of authorisation.  Pass user to fitbit to authorise app (fitbit client id/secret required which are stored in web.config)
        /// </summary>
        /// <returns></returns>
        public ActionResult Authorize()
        {
            var authenticator = new OAuth2Helper(FitbitHelper.GetFitbitAppCredentials(), Request.Url.GetLeftPart(UriPartial.Authority) + "/Fitbit/Callback");

            string[] scopes = new string[] { "profile", "heartrate", "nutrition", "sleep", "weight" };

            string authUrl = authenticator.GenerateAuthUrl(scopes, null);

            return(Redirect(authUrl));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Put string
        /// </summary>
        /// <param name="url"></param>
        /// <param name="content"></param>
        /// <param name="settings">OAuth2Settings</param>
        /// <returns>response</returns>
        public static string HttpPut(string url, string content, OAuth2Settings settings)
        {
            var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.PUT, url, settings);

            byte[] data = Encoding.UTF8.GetBytes(content);
            using (var requestStream = webRequest.GetRequestStream()) {
                requestStream.Write(data, 0, data.Length);
            }
            return(NetworkHelper.GetResponseAsString(webRequest));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Do the actual upload to Box
        /// For more details on the available parameters, see: http://developers.box.net/w/page/12923951/ApiFunction_Upload%20and%20Download
        /// </summary>
        /// <param name="image">Image for box upload</param>
        /// <param name="title">Title of box upload</param>
        /// <param name="filename">Filename of box upload</param>
        /// <returns>url to uploaded image</returns>
        public static string UploadToBox(SurfaceContainer image, string title, string filename)
        {
            // Fill the OAuth2Settings
            var settings = new OAuth2Settings
            {
                AuthUrlPattern     = "https://app.box.com/api/oauth2/authorize?client_id={ClientId}&response_type=code&state={State}&redirect_uri={RedirectUrl}",
                TokenUrl           = "https://api.box.com/oauth2/token",
                CloudServiceName   = "Box",
                ClientId           = BoxCredentials.ClientId,
                ClientSecret       = BoxCredentials.ClientSecret,
                RedirectUrl        = "https://www.box.com/home/",
                BrowserSize        = new Size(1060, 600),
                AuthorizeMode      = OAuth2AuthorizeMode.EmbeddedBrowser,
                RefreshToken       = Config.RefreshToken,
                AccessToken        = Config.AccessToken,
                AccessTokenExpires = Config.AccessTokenExpires
            };


            // Copy the settings from the config, which is kept in memory and on the disk

            try {
                var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.POST, UploadFileUri, settings);
                IDictionary <string, object> parameters = new Dictionary <string, object>();
                parameters.Add("file", image);
                parameters.Add("parent_id", Config.FolderId);

                NetworkHelper.WriteMultipartFormData(webRequest, parameters);

                var response = NetworkHelper.GetResponseAsString(webRequest);

                Log.DebugFormat("Box response: {0}", response);

                var upload = JsonSerializer.Deserialize <Upload>(response);
                if (upload?.Entries == null || upload.Entries.Count == 0)
                {
                    return(null);
                }

                if (Config.UseSharedLink)
                {
                    string filesResponse = HttpPut(string.Format(FilesUri, upload.Entries[0].Id), "{\"shared_link\": {\"access\": \"open\"}}", settings);
                    var    file          = JsonSerializer.Deserialize <FileEntry>(filesResponse);
                    return(file.SharedLink.Url);
                }
                return($"http://www.box.com/files/0/f/0/1/f_{upload.Entries[0].Id}");
            } finally {
                // Copy the settings back to the config, so they are stored.
                Config.RefreshToken       = settings.RefreshToken;
                Config.AccessToken        = settings.AccessToken;
                Config.AccessTokenExpires = settings.AccessTokenExpires;
                Config.IsDirty            = true;
                IniConfig.Save();
            }
        }
        /// <summary>初期化</summary>
        private void Init()
        {
            this.OAuthAuthorizeEndpoint =
                ASPNETIdentityConfig.OAuth2AuthorizationServerEndpointsRootURI
                + ASPNETIdentityConfig.OAuth2AuthorizeEndpoint;

            this.ClientId = OAuth2Helper.GetInstance().GetClientIdByName("TestClient");
            this.State    = GetPassword.Generate(10, 0); // 記号は入れない。
            this.Nonce    = GetPassword.Generate(20, 0); // 記号は入れない。

            this.CodeVerifier  = "";
            this.CodeChallenge = "";
        }
Ejemplo n.º 18
0
        public async Task <ActionResult> Callback(string code)
        {
            var authenticator = new OAuth2Helper(_appCredentials, ConfigurationManager.AppSettings["BaseUrl"] + "/band/callback");

            OAuth2AccessToken accessToken = await authenticator.ExchangeAuthCodeForAccessTokenAsync(code);

            if (!string.IsNullOrEmpty(accessToken.Token))
            {
                _bandClient = GetBandClient(accessToken);
            }

            return(RedirectToAction("Profile"));
        }
Ejemplo n.º 19
0
        public ActionResult AuthorizationCode_PKCE_S256()
        {
            this.Init();
            this.CodeVerifier  = GetPassword.Base64UrlSecret(50);
            this.CodeChallenge = OAuth2Helper.PKCE_S256_CodeChallengeMethod(this.CodeVerifier);
            this.Save();

            // Authorization Code Flow (PKCE S256)
            return(Redirect(this.AssembleOAuth2Starter(
                                ASPNETIdentityConst.AuthorizationCodeResponseType)
                            + "&code_challenge=" + this.CodeChallenge
                            + "&code_challenge_method=S256"));
        }
Ejemplo n.º 20
0
        public void OAuth2Helper_Throws_FitbitTokenException()
        {
            string content = SampleDataHelper.GetContent("ApiError-Request-StaleToken.json");

            try
            {
                OAuth2Helper.ParseAccessTokenResponse(content);
            }
            catch (FitbitException exception)
            {
                // can only use ShouldThrow on async funcs of Task
                exception.ApiErrors.Count.Should().Be(1);
            }
        }
Ejemplo n.º 21
0
        //Final step. Take this authorization information and use it in the app
        /// <summary>
        /// Part 2 of authorisation.  User has (hopefully) accepted request and fitbit passed authorisation code.
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> Callback()
        {
            FitbitAppCredentials appCredentials = FitbitHelper.GetFitbitAppCredentials();
            var    authenticator = new OAuth2Helper(appCredentials, Request.Url.GetLeftPart(UriPartial.Authority) + "/Fitbit/Callback");
            string code          = Request.Params["code"];

            // ask for access token.
            OAuth2AccessToken accessToken = await authenticator.ExchangeAuthCodeForAccessTokenAsync(code);

            // save token (user may have previously authorised in which case update)
            FitbitHelper.AddOrUpdateUser(_unitOfWork, User.Identity.GetUserId(), accessToken);

            return(View("Home", PopulateModel()));
        }
Ejemplo n.º 22
0
        public object GetAuthCode(string code)
        {
            var authorization = "Basic Y2xpZW50X2lkOjljZmZlMzg2ZjFiZGQ5NjZjZmZhOTY1OTJhN2NhYzky";
            var contenttype   = "application/x-www-form-urlencoded";
            var redirectURI   = "http://localhost:50195/api/fitbit/callback";
            //var redirectURI = "https://testfit.azurewebsites.net/api/fitbit/callback";
            var queryParams = "client_id=" + OAuthClientID + "&grant_type=authorization_code&redirect_uri=" + redirectURI + "&code=" + code;



            var appCredentials = new FitbitAppCredentials()
            {
                ClientId     = ConfigurationManager.AppSettings["FitbitClientId"],
                ClientSecret = ConfigurationManager.AppSettings["FitbitClientSecret"]
            };
            //make sure you've set these up in Web.Config under <appSettings>:

            //Session["AppCredentials"] = appCredentials;

            //Provide the App Credentials. You get those by registering your app at dev.fitbit.com
            //Configure Fitbit authenticaiton request to perform a callback to this constructor's Callback method
            var authenticator = new OAuth2Helper(appCredentials, redirectURI);

            string[] scopes = new string[] { "profile", "activity", "heartrate", "location", "nutrition", "settings", "sleep", "social", "weight" };

            string authUrl = authenticator.GenerateAuthUrl(scopes, null);

            return(Redirect(authUrl));

            /*
             * HttpClient client = new HttpClient();
             * client.BaseAddress = new Uri(AccessTokenRefreshURI);
             *
             * client.DefaultRequestHeaders.Accept
             *      .Add(new MediaTypeWithQualityHeaderValue(contenttype));//ACCEPT header
             * client.DefaultRequestHeaders.Add("Authorization", authorization);
             *
             * HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, queryParams);
             *
             * client.SendAsync(request)
             *        .ContinueWith(responseTask =>
             *        {
             *                var response = responseTask.Result;
             *                return response;
             *        });
             *
             * return null;
             */
        }
Ejemplo n.º 23
0
        private void Load()
        {
            try
            {
                OAuth2Helper authenticator = new OAuth2Helper("227H9T", "74e4a047fce979dd36a0edbd626c3939", "http://Miriot.suismoi.fr");
                string[]     scopes        = new[] { "profile", "weight" };

                string authUrl = authenticator.GenerateAuthUrl(scopes, null);

                WebView browser = new WebView();
                browser.Height = 300;
                browser.Width  = 300;
                browser.Source = new Uri(authUrl);
                browser.DefaultBackgroundColor = Colors.Black;
                MainGrid.Children.Add(browser);

                browser.NavigationStarting += async(s, args) =>
                {
                    if (args.Uri.OriginalString.Contains("code="))
                    {
                        var code = args.Uri.Query.Replace("?code=", "");
                        AccessToken = await authenticator.ExchangeAuthCodeForAccessTokenAsync(code);

                        AccessToken = await authenticator.RefreshToken(AccessToken.RefreshToken);

                        MainGrid.Children.Remove(browser);

                        try
                        {
                            var w = await GetWeightAsync(DateTime.Now, null);

                            Value.Text = $"{w.Weight.First().Weight}kg";
                        }
                        catch (Exception ex)
                        {
                            // Access denied ?
                            Debug.WriteLine(ex.Message);
                        }
                    }
                };
            }
            catch (Exception ex)
            {
                // Something went wrong
                Debug.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 24
0
        public async Task <IHttpActionResult> RegistrationResult(string code)
        {
            FitbitAppCredentials appCredentials = (FitbitAppCredentials)session[AppCredentials];

            var authenticator = new OAuth2Helper(appCredentials, $"{Request.RequestUri.GetLeftPart(UriPartial.Authority)}/fitbit/{nameof(RegistrationResult).ToLowerInvariant()}");

            OAuth2AccessToken accessToken = await authenticator.ExchangeAuthCodeForAccessTokenAsync(code);

            // Store credentials in FitbitClient. The client in its default implementation manages the Refresh process
            var fitbitClient = GetFitbitClient(accessToken);

            // register a subscription for the authorized user
            // TODO: Remove hardcoded subscriber id -- should be the equivalent of our user id
            await fitbitClient.AddSubscriptionAsync(APICollectionType.user, "123456789");

            return(Ok());
        }
Ejemplo n.º 25
0
        //Final step. Take this authorization information and use it in the app
        public async Task <ActionResult> Callback()
        {
            FitbitAppCredentials appCredentials = (FitbitAppCredentials)Session["AppCredentials"];

            var authenticator = new OAuth2Helper(appCredentials, Request.Url.GetLeftPart(UriPartial.Authority) + "/Fitbit/Callback");

            string code = Request.Params["code"];

            OAuth2AccessToken accessToken = await authenticator.ExchangeAuthCodeForAccessTokenAsync(code);

            //Store credentials in FitbitClient. The client in its default implementation manages the Refresh process
            var fitbitClient = GetFitbitClient(accessToken);

            ViewBag.AccessToken = accessToken;

            return(View());
        }
Ejemplo n.º 26
0
        async void Browser_Navigated(object sender, WebNavigatedEventArgs e)
        {
            //verify callback URL
            Debug.WriteLine(e.Url);

            Uri url = new Uri(e.Url);

            if (url.Host.Contains("example.com"))
            {
                //parse the response
                var code  = HttpUtility.ParseQueryString(url.Query).Get("code");
                var error = HttpUtility.ParseQueryString(url.Query).Get("error");
                //exchange this for a token
                Debug.WriteLine("Got Code: " + code);

                if (error != null)
                {
                    Debug.WriteLine("Error with logging user in");
                    await DisplayAlert("Uh-oh", "There was trouble logging you in", "Try Again");

                    Browser.Source = URL;

                    await Navigation.PopAsync();
                }

                //To-do: Exchange the code for an access token
                Device.BeginInvokeOnMainThread(async() =>
                {
                    //Save the RefreshToken and set App AccessToken and LastRefreshedTime
                    var postbackURL = "https://accounts.spotify.com/api/token";
                    var tokens      = await OAuth2Helper.GetAccessTokenFromCode(postbackURL,
                                                                                Credentials.RedirectURI,
                                                                                Credentials.ClientID,
                                                                                Credentials.ClientSecret,
                                                                                Credentials.Scopes,
                                                                                code);

                    //In App.cs, add these variables to maintain context
                    App.HasLoggedIn = true;
                    App.AuthModel   = tokens;

                    await Navigation.PushModalAsync(new ProfilePage());
                });
            }
        }
Ejemplo n.º 27
0
        public IHttpActionResult Authorize()
        {
            var appCredentials = new FitbitAppCredentials()
            {
                ClientId     = clientId,
                ClientSecret = clientSecret
            };

            session[AppCredentials] = appCredentials;

            // provide the App Credentials. You get those by registering your app at dev.fitbit.com
            // configure Fitbit authenticaiton request to perform a callback to this controller's result method
            var authenticator = new OAuth2Helper(appCredentials, $"{Request.RequestUri.GetLeftPart(UriPartial.Authority)}/fitbit/{nameof(RegistrationResult).ToLowerInvariant()}");

            string[] scopes = Enum.GetValues(typeof(FitbitAuthScope)).Cast <FitbitAuthScope>().Select(x => x.ToString().ToLowerInvariant()).ToArray();

            string authUrl = authenticator.GenerateAuthUrl(scopes, null);

            return(Redirect(authUrl));
        }
        public async Task <ActionResult> LandingExternal(MsalOauthResponse response)
        {
            if (string.IsNullOrWhiteSpace(response.Code))
            {
                return(Json(response, "application/json", JsonRequestBehavior.AllowGet));
            }
            var state = OAuth2Helper.ParseState(response.State);

            if (state.ClientId == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.ExpectationFailed,
                                                "Invalid session data returned after login from M365"));
            }

            var tenant = await _mediator.Send(new QueryTenantByClientId(state.ClientId));

            if (tenant.TenantId != state.Tenant)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.ExpectationFailed,
                                                "Invalid tenant returned after login from M365"));
            }
            var tokenResponse = await OAuth2Helper.AcquireTokenAsync(new AcquireTokenRequest
            {
                Tenant       = tenant.TenantId,
                ClientId     = tenant.ClientId,
                Secret       = tenant.Secret,
                ResponseCode = response.Code,
                CodeVerifier = state.CodeVerifier,
                RedirectUri  = $"{Request.GetBaseUrl()}{Url.Action("LandingExternal")}"
            });

            await _mediator.Send(new SaveEmailAccountTokenCommand
            {
                Email        = state.Email,
                AccessToken  = tokenResponse.AccessToken,
                RefreshToken = tokenResponse.RefreshToken
            });

            return(View(tokenResponse));
        }
Ejemplo n.º 29
0
        //
        // GET: /Authorize/
        // Setup - prepare the user redirect to Fitbit.com to prompt them to authorize this app.
        public async Task <ActionResult> Authorize()
        {
            //make sure you've set these up in Web.Config under <appSettings>:
            var appCredentials = new FitbitAppCredentials()
            {
                ClientId     = ConfigurationManager.AppSettings["FitbitConsumerKey"],
                ClientSecret = ConfigurationManager.AppSettings["FitbitConsumerSecret"]
            };

            //Provide the App Credentials. You get those by registering your app at dev.fitbit.com
            //Configure Fitbit authenticaiton request to perform a callback to this constructor's Callback method
            var authenticator = new OAuth2Helper(appCredentials, Request.Url?.GetLeftPart(UriPartial.Authority) + "/Fitbit/Callback");

            string[] scopes = new string[] { "profile" };

            Session["FitbitAuthenticator"] = authenticator;

            //note: at this point the RequestToken object only has the Token and Secret properties supplied. Verifier happens later.
            string authUrl = authenticator.GenerateAuthUrl(scopes);

            return(Redirect(authUrl));
        }
Ejemplo n.º 30
0
        //
        // GET: /FitbitAuth/
        // Setup - prepare the user redirect to Fitbit.com to prompt them to authorize this app.
        public ActionResult Authorize()
        {
            var appCredentials = new FitbitAppCredentials()
            {
                ClientId     = ConfigurationManager.AppSettings["FitbitClientId"],
                ClientSecret = ConfigurationManager.AppSettings["FitbitClientSecret"]
            };

            //make sure you've set these up in Web.Config under <appSettings>:

            Session["AppCredentials"] = appCredentials;

            //Provide the App Credentials. You get those by registering your app at dev.fitbit.com
            //Configure Fitbit authenticaiton request to perform a callback to this constructor's Callback method
            var authenticator = new OAuth2Helper(appCredentials, Request.Url.GetLeftPart(UriPartial.Authority) + "/Fitbit/Callback");

            string[] scopes = new string[] { "profile", "weight", "activity", "sleep" };

            string authUrl = authenticator.GenerateAuthUrl(scopes, null);

            return(Redirect(authUrl));
        }