Ejemplo n.º 1
0
        public static async Task <string> GenerateTokenFromOAuth(GitHubClient Client, string ClientID, string ClientSecret, string Code)
        {
            OauthTokenRequest Request = new OauthTokenRequest(ClientID, ClientSecret, Code);
            OauthToken        Token   = await Client.Oauth.CreateAccessToken(Request);

            return(Token.AccessToken);
        }
Ejemplo n.º 2
0
        public async Task <string> GetAccessTokenAsync(string code)
        {
            var        authRequest = new OauthTokenRequest(_settings.GitHub.ClientId, _settings.GitHub.ClientSecret, code);
            OauthToken token       = await _client.Oauth.CreateAccessToken(authRequest);

            return(token.AccessToken);
        }
Ejemplo n.º 3
0
        public async Task <IEnumerable <GithubUser> > GetUser(string temporaryCode)
        {
            var clientSecret = Environment.GetEnvironmentVariable(ClientSecretEnvironmentKey);
            var clientId     = Environment.GetEnvironmentVariable(ClientIdEnvironmentKey);

            var client = new GitHubClient(
                new ProductHeaderValue(Environment.GetEnvironmentVariable(AppNameEnvironmentKey)));

            var request = new OauthTokenRequest(clientId, clientSecret, temporaryCode);

            var token = await client.Oauth.CreateAccessToken(request);

            HttpContext.Session.SetString(TokenSessionKey, token.AccessToken);

            client.Credentials = new Credentials(token.AccessToken);

            var currentUser = await client.User.Current();

            return(new[]
            {
                new GithubUser
                {
                    Name = currentUser.Name,
                    AvatarUrl = currentUser.AvatarUrl
                }
            });
        }
Ejemplo n.º 4
0
        /// <inheritdoc/>
        public async Task <LoginResult> LoginViaOAuth(
            HostAddress hostAddress,
            IGitHubClient client,
            IOauthClient oauthClient,
            Action <Uri> openBrowser,
            CancellationToken cancel)
        {
            Guard.ArgumentNotNull(hostAddress, nameof(hostAddress));
            Guard.ArgumentNotNull(client, nameof(client));
            Guard.ArgumentNotNull(oauthClient, nameof(oauthClient));
            Guard.ArgumentNotNull(openBrowser, nameof(openBrowser));

            var state    = Guid.NewGuid().ToString();
            var loginUrl = GetLoginUrl(oauthClient, state);
            var listen   = oauthListener.Listen(state, cancel);

            openBrowser(loginUrl);

            var code = await listen.ConfigureAwait(false);

            var request = new OauthTokenRequest(clientId, clientSecret, code);
            var token   = await oauthClient.CreateAccessToken(request).ConfigureAwait(false);

            await keychain.Save("[oauth]", token.AccessToken, hostAddress).ConfigureAwait(false);

            var result = await ReadUserWithRetry(client).ConfigureAwait(false);

            await keychain.Save(result.User.Login, token.AccessToken, hostAddress).ConfigureAwait(false);

            return(result);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// code=92753cc957561014b8ef&state=%5BbKCBfYvK.%2BD_2dc0KLyy%243-
        /// </summary>
        /// <returns></returns>
        public ActionResult Authorize(string code, string state)
        {
            try
            {
                var client = AppConfig.Current.GetClient();


                if (String.IsNullOrEmpty(code))
                {
                    return(RedirectToAction("Index"));
                }

                var expectedState = Session["CSRF:State"] as string;
                if (state != expectedState)
                {
                    throw new InvalidOperationException("SECURITY FAIL!");
                }
                Session["CSRF:State"] = null;

                var request = new OauthTokenRequest(AppConfig.Current.ClientId, AppConfig.Current.ClientSecret, code);
                var token   = client.Oauth.CreateAccessToken(request).Result;
                Session["OAuthToken"] = token.AccessToken;



                return(new RedirectResult("~/Stats/"));
            }
            catch (Exception exc)
            {
                Response.Write(exc.Message);
                Response.Write(exc.StackTrace);
                Response.End();
                throw new Exception("Not reachable code");
            }
        }
Ejemplo n.º 6
0
        public async Task <ActionResult> GithubAuthorized(string code, string state, [FromServices] AreaDbContext DB)
        {
            string username = HttpContext.Session.GetString("username");

            if (String.IsNullOrEmpty(username))
            {
                return(Redirect("http://localhost:5000"));
            }
            try {
                var clientId     = "Iv1.81c9b324b18a4188";
                var clientSecret = "d480b95d45b1147557bf97f51f87d0f4f7f9c14a";
                var client       = new GitHubClient(new ProductHeaderValue("AreaNet"));
                if (String.IsNullOrEmpty(code))
                {
                    return(Redirect("http://localhost:5000"));
                }
                var request = new OauthTokenRequest(clientId, clientSecret, code);
                var token   = await client.Oauth.CreateAccessToken(request);

                DB.tokens.Add(new Models.Token {
                    type = "Github", username = username, value = token.AccessToken
                });
                DB.SaveChanges();
            }
            catch
            {
                Console.WriteLine("Error in GithubAuthorize");
                return(Redirect("http://localhost:5000"));
            }
            return(Redirect("http://localhost:5000"));
        }
Ejemplo n.º 7
0
        public string OAuthAuthorize(string code, string state)
        {
            var request = new OauthTokenRequest(clientId, clientSecret, code);
            var token   = client.Oauth.CreateAccessToken(request).Result;

            return(token.AccessToken);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Makes call for Access Token
        /// </summary>
        /// <param name="response">Response string containing 'code' token, used for getting access token</param>
        /// <returns></returns>
        private async Task <bool> Authorize(string response)
        {
            try
            {
                string   responseData = response.Substring(response.IndexOf("code"));
                string[] keyValPairs  = responseData.Split('=');
                string   code         = keyValPairs[1].Split('&')[0];


                string clientId = await AppCredentials.GetAppKey();

                string appSecret = await AppCredentials.GetAppSecret();

                var request = new OauthTokenRequest(clientId, appSecret, code);
                var token   = await client.Oauth.CreateAccessToken(request);

                if (token != null)
                {
                    client.Credentials = new Credentials(token.AccessToken);
                    await SaveToken(token.AccessToken, clientId);
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 9
0
        public async Task <RedirectResult> IssueToken(string code, string state)
        {
            // Oauth認証時に格納したユーザデータを取得
            NameValueCollection data = _userData;

            // ===========================
            // GitHubアクセストークン発行
            // ===========================
            var request = new OauthTokenRequest(ConfigurationManager.AppSettings["client_id"], ConfigurationManager.AppSettings["client_secret"], code);

            var token = await _githubClient.Oauth.CreateAccessToken(request);

            // ============================================
            // slackユーザとGitHubアクセストークンの紐付け
            // ============================================
            var entityOperationUser = new EntityOperation <UserEntity>();

            //作成or更新を行うユーザエンティティ作成
            var entity = new UserEntity(data["user_id"], data["user_name"], token.AccessToken);

            //エンティティを操作変数を用いて作成or更新
            entityOperationUser.InsertOrUpdateEntityResult(entity, "user");

            return(Redirect("https://" + data["team_domain"] + ".slack.com/messages"));
        }
Ejemplo n.º 10
0
        public async Task <OauthToken> OAuthAccessToken(string code)
        {
            var request = new OauthTokenRequest(clientId, clientSecret, code);
            var token   = await Git.Oauth.CreateAccessToken(request);

            return(token);
        }
Ejemplo n.º 11
0
        public async static Task <string> GenerateToken(string code)
        {
            var request = new OauthTokenRequest(Const.clientId, Const.clientSecret, code);
            var token   = await Core.client.Oauth.CreateAccessToken(request);

            return(token.AccessToken);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Generates an access token give a response URL from the user log in.
        /// </summary>
        /// <param name="responseUrl">User log in response URL</param>
        /// <returns>String containing the access token of the user</returns>
        static public async Task <string> GetAccessToken(string responseUrl)
        {
            var code    = getCodeFromUrl(responseUrl);
            var request = new OauthTokenRequest(ApiKeys.API_KEY, ApiKeys.API_SECRET, code);
            var token   = await client.Oauth.CreateAccessToken(request);

            return(token.AccessToken);
        }
Ejemplo n.º 13
0
        public async Task <string> CreateAccessToken(string id, string secret, string code)
        {
            var request = new OauthTokenRequest(id, secret, code);

            OauthToken token = await client.Oauth.CreateAccessToken(request);

            return(token.AccessToken);
        }
Ejemplo n.º 14
0
        public async Task <OauthToken> GetOauthAccessToken(string clientId, string clientSecret, string code)
        {
            Trace.TraceInformation("Obtaining OAuth Access Token");

            var request = new OauthTokenRequest(clientId, clientSecret, code);
            var token   = await GitHubClient().Oauth.CreateAccessToken(request);

            Trace.TraceInformation($"Token obtained for {(await GetUser(token.AccessToken)).Username}");
            return(token);
        }
Ejemplo n.º 15
0
        public async Task <ContentResult> Complete(string code)
        {
            ;
            var request = new OauthTokenRequest(_settings.ClientId, _settings.ClientSecret, code);
            var token   = await _clientFactory().Oauth.CreateAccessToken(request).ConfigureAwait(false);

            return(Content($@"<script>
                localStorage['sharplab.github.token'] = '{token.AccessToken}';
                window.location.href = sessionStorage['sharplab.github.auth.return'];
            </script>", MediaTypeNames.Text.Html));
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Gets Fired whenever a page in the WebView finishes loading.
 /// </summary>
 /// <param name="view"></param>
 /// <param name="url"></param>
 public override void OnPageFinished(WebView view, string url)
 {
     base.OnPageFinished(view, url);
     if (url.Contains("code="))
     {
         var code = url.Split(new[] { "code=" }, StringSplitOptions.None)[1];
         code = code.Replace("&state=", string.Empty);
         var tokenRequest = new OauthTokenRequest(_clientId, _clientSecret, code);
         var accessToken  = _client.Oauth.CreateAccessToken(tokenRequest).Result;
         CrossSecureStorage.Current.SetValue("OAuthToken", accessToken.AccessToken.ToString());
     }
 }
Ejemplo n.º 17
0
        /// <inheritdoc />
        public async Task <string> CompleteAuthorization(HttpRequest request, IResponseCookies cookies, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (cookies == null)
            {
                throw new ArgumentNullException(nameof(cookies));
            }


            string code;

            if (!request.Query.TryGetValue("code", out StringValues stringValues) || stringValues.Count == 0)
            {
                return(null);
            }
            code = stringValues.First();

            logger.LogTrace("CompleteAuthorization for with code: {0}", code);


            var otr          = new OauthTokenRequest(gitHubConfiguration.OauthClientID, gitHubConfiguration.OauthSecret, code);
            var gitHubClient = gitHubClientFactory.CreateAppClient();
            var result       = await gitHubClient.Oauth.CreateAccessToken(otr).ConfigureAwait(false);

            if (result.AccessToken == null)
            {
                //user is f*****g with us, don't even bother
                return(null);
            }

            var expiry   = DateTimeOffset.UtcNow.AddDays(AccessTokenExpiryDays);
            var newEntry = new UserAccessToken
            {
                Id          = Guid.NewGuid(),
                AccessToken = result.AccessToken,
                Expiry      = expiry
            };

            await databaseContext.UserAccessTokens.AddAsync(newEntry, cancellationToken).ConfigureAwait(false);

            await databaseContext.Save(cancellationToken).ConfigureAwait(false);

            cookies.Append(AuthorizationCookie, newEntry.Id.ToString());

            if (request.Query.TryGetValue("state", out stringValues) && stringValues.Count > 0)
            {
                return(stringValues.First());
            }
            return(null);
        }
Ejemplo n.º 18
0
        public async override Task Invoke(IOwinContext context)
        {
            var code    = context.Request.Query["code"];
            var request = new OauthTokenRequest(_settings.ClientId, _settings.ClientSecret, code);
            var token   = await _clientFactory().Oauth.CreateAccessToken(request).ConfigureAwait(false);

            context.Response.ContentType = "text/html";
            await context.Response.WriteAsync($@"<script>
                localStorage['sharplab.github.token'] = '{token.AccessToken}';
                window.location.href = sessionStorage['sharplab.github.auth.return'];
            </script>").ConfigureAwait(false);
        }
Ejemplo n.º 19
0
        public static async Task <string> ProcessBrowserCodeResponseAsync(string code)
        {
            var tokenRequest = new OauthTokenRequest(
                GitHubClientBase.ClientId,
                GitHubClientBase.ClientSecret.FromHex(),
                code
                );

            var token = await GitHubClientBase.Instance.Oauth.CreateAccessToken(tokenRequest);

            return(token.AccessToken);
        }
        /// <inheritdoc/>
        public override void ConfigureAuthenticationModule(NancyModule module)
        {
            module.Get["/auth/{token}"] = args =>
            {
                User user;
                if (!User.TryGetByToken(args.token, out user))
                {
                    return(HttpStatusCode.BadRequest);
                }

                var request = new OauthLoginRequest(ClientId)
                {
                    RedirectUri = new Uri(Domain, "auth/after-auth/" + user.Token)
                };
                request.Scopes.Add("repo");
                request.Scopes.Add("user:email");

                return(module.Response.AsRedirect(authClient.Oauth.GetGitHubLoginUrl(request).AbsoluteUri));
            };

            module.Get["/after-auth/{token}", true] = async(args, ct) =>
            {
                User user;
                if (!User.TryGetByToken(args.token, out user))
                {
                    // Eh, well.
                    return(HtmlHelpers.CreateHtmlPage(
                               "Session expired",
                               "<h1>Oops.</h1> <div>Something went wrong. Your session token probably expired. " +
                               "Trying again might work.</div>"));
                }

                // Extend the user's lifetime so they don't die on us.
                user.ExtendLifetime(AuthenticationModule.AuthenticatedUserLifetime);

                // Request an OAuth token.
                var request = new OauthTokenRequest(
                    ClientId,
                    ClientSecret,
                    module.Request.Query.code);

                // Store it.
                user.ContentTrackerToken = new GitHubContentTrackerToken(
                    await authClient.Oauth.CreateAccessToken(request));

                return(HtmlHelpers.CreateHtmlPage(
                           "Authentication successful",
                           "<h1>You did it!</h1> <div>Yay! You successfully managed to authenticate! 🎉</div>"));
            };
        }
Ejemplo n.º 21
0
        // GET api/<controller>
        public async Task <RedirectResult> Get(string code, string state)
        {
            //stateに相違がある場合はセキュリティエラー
            if (state != LoginDialog.csrf)
            {
                throw new InvalidOperationException("SECURITY FAIL!");
            }

            //tokenのリクエストを作成
            var request = new OauthTokenRequest(ConfigurationManager.AppSettings["client_id"], ConfigurationManager.AppSettings["client_secret"], code);

            //リクエストを送信
            var token = await GitHubDialog.github.Oauth.CreateAccessToken(request);

            //ユーザエンティティの操作変数作成
            EntityOperation <UserEntity> entityOperation_Template = new EntityOperation <UserEntity>();

            //作成or更新を行うユーザエンティティ作成
            UserEntity entity = new UserEntity(GitHubDialog.activity.From.Id, GitHubDialog.activity.From.Name, token.AccessToken);

            //エンティティを操作変数を用いて作成or更新
            TableResult result = entityOperation_Template.InsertOrUpdateEntityResult(entity, "user");

            #region 未使用API送信
            ////API送信用ウェブクライアント
            //using (WebClient wc = new WebClient())
            //{
            //    //必要なクエリ情報を作成し、格納
            //    NameValueCollection nvc = new NameValueCollection();
            //    nvc.Add("client_id", ConfigurationManager.AppSettings["client_id"]);
            //    nvc.Add("client_secret", ConfigurationManager.AppSettings["client_secret"]);
            //    nvc.Add("code", code);
            //    nvc.Add("state", state);
            //    wc.QueryString = nvc;

            //    //データを送信し、また受信する
            //    byte[] response =  wc.UploadValues("https://github.com/login/oauth/access_token", nvc);

            //    //文字列化した受信バイトデータをNameValueCollectionに換装
            //    nvc = HttpUtility.ParseQueryString(wc.Encoding.GetString(response));

            //    GitHubDialog.accessToken = nvc.Get("access_token");

            //    return Redirect("https://slack.com");
            //}
            #endregion

            return(Redirect("https://" + GitHubDialog.channelName + ".slack.com"));
        }
Ejemplo n.º 22
0
        protected internal async Task RegisterUserToken(RegisterTokenModel data)
        {
            if (ValidateSecret(data.Secret))
            {
                var githubClient = new GitHubClient(new ProductHeaderValue("sharp-linker"));
                var request      = new OauthTokenRequest(clientId, clientSecret, data.Code);
                var token        = await githubClient.Oauth.CreateAccessToken(request);

                var response = new Message
                {
                    Action = "Token",
                    Data   = token.AccessToken
                };
                BroadcastMessage(response, data.ClientId);
            }
        }
Ejemplo n.º 23
0
        public async Task Handle(HttpRequest request, HttpResponse response, RouteData routeData)
        {
            // We should know the TenantID and user ID here
            Console.WriteLine("CODE: " + request.Query["code"]);
            Console.WriteLine("STATE: " + request.Query["state"]);

            var tokenRequest = new OauthTokenRequest(_credentials.OAuthClientID, _credentials.OAuthClientSecret, request.Query["code"]);
            var client       = await _clientFactory.NewApplicationAuthenticatedClient();

            var token = await client.Oauth.CreateAccessToken(tokenRequest);

            var callback = _tokenStore.SetTokenForCurrentUser(request.Query["state"].Single(), token);

            response.StatusCode          = StatusCodes.Status307TemporaryRedirect;
            response.Headers["Location"] = callback;
        }
Ejemplo n.º 24
0
        public async Task <ActionResult> Authorize(string code, string state)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(RedirectToAction("Index"));
            }
            else
            {
                var csrf = HttpContext.Session.GetString(SESSION_CSRF_KEY);
                if (state != csrf)
                {
                    _logger.LogWarning($"Authentication failure, callback state did not match session CSRF token.");
                    TempData["Error"] = "Authentication failure due to incorrect CSRF token.";
                    return(RedirectToAction(nameof(Index)));
                }
                else
                {
                    HttpContext.Session.Remove(SESSION_CSRF_KEY);

                    var client  = new GitHubClient(new ProductHeaderValue(_githubAppName));
                    var request = new OauthTokenRequest(_githubClientID, _githubClientSecret, code);
                    var token   = await client.Oauth.CreateAccessToken(request);

                    client.Credentials = new Credentials(token.AccessToken);

                    var user = await client.User.Current();

                    _logger.LogDebug($"GitHub authenticated user ID: {user.Id}.");

                    var claims = new List <Claim>
                    {
                        new Claim("user", user.Id.ToString()),
                        new Claim("role", "Member"),
                    };

                    if (_adminUsers?.Contains(user.Id.ToString()) == true)
                    {
                        _logger.LogDebug($"GitHub user {user.Id} set as admin.");
                        claims.Add(new Claim("role", "Admin"));
                    }

                    await HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies", "user", "role")));

                    return(RedirectToAction(nameof(Account)));
                }
            }
        }
Ejemplo n.º 25
0
        public async Task ObtainNewToken()
        {
            if (client.Credentials.AuthenticationType == AuthenticationType.Basic)
            {
                throw new InvalidOperationException("Cannot obtain new token for non-oauth session!");
            }
            var request = new OauthTokenRequest(clientId, clientSecret, Code);

            if (server.isCancelled)
            {
                return;
            }
            Token = await client.Oauth.CreateAccessToken(request);

            session["OAuthToken"] = Token.AccessToken;
            client.Credentials    = new Credentials(Token.AccessToken);
        }
Ejemplo n.º 26
0
        public ActionResult Auth(string code)
        {
            code = Request.QueryString["code"];

            var oauthTokenRequest = new OauthTokenRequest(_clientId, _clientSecret, code)
            {
                RedirectUri = new Uri("http://localhost/Cato.Web/home/auth")
            };

            var oauthToken = _github.Oauth.CreateAccessToken(oauthTokenRequest).Result;

            //github.Credentials = new Credentials(oauthToken.AccessToken);

            Session["token"] = oauthToken.AccessToken;

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Retrieves code value from a given string and uses it to create access token and then saves it.
        /// </summary>
        /// <param name="retrievedUrl">Url from browser</param>
        /// <returns></returns>
        private async Task CodeRetrieverandTokenSaver(string retrievedUrl)
        {
            //Retrieves code from URL
            var code = retrievedUrl.Split(new[] { "code=" }, StringSplitOptions.None)[1];

            code = code.Replace("&state=", string.Empty);
            var tokenRequest = new OauthTokenRequest(_clientId, _clientSecret, code);
            var accessToken  = await _client.Oauth.CreateAccessToken(tokenRequest);

            if (CrossSecureStorage.Current != null)
            {
                CrossSecureStorage.Current.SetValue("OAuthToken", accessToken.AccessToken);
            }
            var msgDialog = new MessageDialog("Choose any page you want to go from the menu on the left or you can just stare at this page. Your choice!", "Login Successful!");
            await msgDialog.ShowAsync();

            LoginProgressBar.Value = 100;
        }
Ejemplo n.º 28
0
        public static async Task Authorize()
        {
            var uri = _client.Oauth.GetGitHubLoginUrl(new OauthLoginRequest(_clientId));

            Process.Start(new ProcessStartInfo("cmd", $"/c start {uri.ToString()}"));
            Console.Write($"\r\nLaunching browser at {uri}.\r\nPlease log in and authorize application.\r\nAfter authorization, you will be redirected to an url that ends with code=[some_code]\r\nPlease copy the code, paste it here, and press enter.\r\n\r\ncode=");
            var code = Console.ReadLine();

            Console.Write("\r\n");

            if (String.IsNullOrEmpty(code))
            {
                return;
            }

            var request = new OauthTokenRequest(_clientId, _clientSecret, code);
            var token   = await _client.Oauth.CreateAccessToken(request);

            File.WriteAllText(_filename, token.AccessToken);
        }
Ejemplo n.º 29
0
        public async Task <HttpResponseMessage> OAuthCallback([FromUri] string code, [FromUri] string state, [FromUri] string cookie, CancellationToken cancellationToken)
        {
            GitHubClient client = new GitHubClient(new ProductHeaderValue(Constants.ProductHeader));

            OauthTokenRequest request = new OauthTokenRequest(ConfigurationManager.AppSettings[Constants.GitHubClientIdKey], ConfigurationManager.AppSettings[Constants.GitHubClientSecretKey], code);
            OauthToken        token   = await client.Oauth.CreateAccessToken(request);

            // Send a message to the conversation to resume the flow
            ConversationReference cr = GetConversationReference(cookie);
            Activity msg             = cr.GetPostToBotMessage();

            msg.Text = "authenticated";

            using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, msg))
            {
                var dataBag = scope.Resolve <IBotData>();
                await dataBag.LoadAsync(cancellationToken);

                string csrf;
                if (dataBag.UserData.TryGetValue(Constants.StateKey, out csrf) && csrf == state)
                {
                    // remove persisted cookie
                    dataBag.UserData.RemoveValue(Constants.StateKey);
                    dataBag.UserData.SetValue(Constants.AuthTokenKey, token.AccessToken);
                    await dataBag.FlushAsync(cancellationToken);

                    // Resume the conversation
                    await Conversation.ResumeAsync(cr, msg);

                    var response = Request.CreateResponse("You are now logged in! Please return to your Bot conversation to continue.");
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                    return(response);
                }

                // no state or state doesn't match
                var responseError = Request.CreateResponse("Invalid state, please try again.");
                responseError.StatusCode = HttpStatusCode.BadRequest;
                responseError.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                return(responseError);
            }
        }
Ejemplo n.º 30
0
        internal async void HandleOAuth(string oAuthUrl)
        {
            try
            {
                var code    = oAuthUrl.Replace("unihub://login?code=", "");
                var request = new OauthTokenRequest(Secret.clientId, Secret.clientSecret, code);

                var token = await SessionManager.Client.Oauth.CreateAccessToken(request);

                SessionManager.AccessToken = token.AccessToken;

                SessionManager.Client.Credentials = new Credentials(SessionManager.AccessToken as string);

                _view.OAuthSucceeded();
            }
            catch (Exception)
            {
                SessionManager.AccessToken = null;
                _view.OAuthFailed();
            }
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Makes a request to get an access token using the code returned when GitHub.com redirects back from the URL
 /// <see cref="GetGitHubLoginUrl">GitHub login url</see> to the application.
 /// </summary>
 /// <remarks>
 /// If the user accepts your request, GitHub redirects back to your site with a temporary code in a code
 /// parameter as well as the state you provided in the previous step in a state parameter. If the states don’t
 /// match, the request has been created by a third party and the process should be aborted. Exchange this for
 /// an access token using this method.
 /// </remarks>
 /// <param name="request"></param>
 /// <returns></returns>
 public IObservable<OauthToken> CreateAccessToken(OauthTokenRequest request)
 {
     return _client.Oauth.CreateAccessToken(request).ToObservable();
 }