Пример #1
0
        public void AwaitCallback(bool generateLocalOutput = false)
        {
            using (HttpServer = new HttpServer(new HttpRequestProvider()))
            {
                HttpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Parse(Host.Equals("localhost")
                    ? IPAddress.Loopback.ToString() : Host), Port)));

                HttpServer.Use((context, next) =>
                {
                    string code  = null;
                    string state = null;
                    try
                    {
                        code  = context.Request.QueryString.GetByName("code");
                        state = context.Request.QueryString.GetByName("state");  // This app formats state as:  AppId + ":" [+ AppSecret]
                    }
                    catch (KeyNotFoundException)
                    {
                        context.Response = new uhttpsharp.HttpResponse(HttpResponseCode.Ok, Encoding.UTF8.GetBytes("<b>ERROR:  No code and/or state received!</b>"), false);
                        throw new Exception("ERROR:  Request received without code and/or state!");
                    }

                    if (!string.IsNullOrWhiteSpace(code) &&
                        !string.IsNullOrWhiteSpace(state))
                    {
                        // Send request with code and JSON-decode the return for token retrieval.  --Kris
                        RestRequest restRequest = new RestRequest("/api/v1/access_token", Method.POST);

                        restRequest.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(state)));
                        restRequest.AddHeader("Content-Type", "application/x-www-form-urlencoded");

                        restRequest.AddParameter("grant_type", "authorization_code");
                        restRequest.AddParameter("code", code);
                        restRequest.AddParameter("redirect_uri",
                                                 "http://" + Host + ":" + Port.ToString() + "/Reddit.NET/oauthRedirect"); // This must be an EXACT match in the app settings on Reddit!  --Kris

                        OAuthToken oAuthToken = JsonConvert.DeserializeObject <OAuthToken>(ExecuteRequest(restRequest));

                        // Set the token properties.  --Kris
                        AccessToken  = oAuthToken.AccessToken;
                        RefreshToken = oAuthToken.RefreshToken;

                        // Fire the auth success event with the token in the event args.  --Kris
                        AuthSuccess?.Invoke(this, new AuthSuccessEventArgs {
                            AccessToken = oAuthToken.AccessToken, RefreshToken = oAuthToken.RefreshToken
                        });

                        // Generate the success page.  --Kris
                        string[] sArr = state.Split(':');
                        if (sArr == null || sArr.Length == 0)
                        {
                            throw new Exception("State must consist of 'appId:appSecret'!");
                        }

                        string appId     = sArr[0];
                        string appSecret = (sArr.Length >= 2 ? sArr[1] : null);

                        string html;
                        using (Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("AuthTokenRetrieverLib.Templates.Success.html"))
                        {
                            using (StreamReader streamReader = new StreamReader(stream))
                            {
                                html = streamReader.ReadToEnd();
                            }
                        }

                        html = html.Replace("REDDIT_OAUTH_ACCESS_TOKEN", oAuthToken.AccessToken);
                        html = html.Replace("REDDIT_OAUTH_REFRESH_TOKEN", oAuthToken.RefreshToken);

                        // If enabled, output the token to a JSON file in the current directory.  --Kris
                        if (generateLocalOutput)
                        {
                            string tokenSavedHtml;
                            using (Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("AuthTokenRetrieverLib.Templates.TokenSaved.html"))
                            {
                                using (StreamReader streamReader = new StreamReader(stream))
                                {
                                    tokenSavedHtml = streamReader.ReadToEnd();
                                }
                            }

                            string fileExt = "." + appId + "." + (!string.IsNullOrWhiteSpace(appSecret) ? appSecret + "." : "") + "json";

                            string tokenPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar
                                               + "RDNOauthToken_" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileExt;

                            File.WriteAllText(tokenPath, JsonConvert.SerializeObject(oAuthToken));

                            html = html.Replace("TOKEN_SAVED", tokenSavedHtml.Replace("LOCAL_TOKEN_PATH", tokenPath));
                        }
                        else
                        {
                            html = html.Replace("TOKEN_SAVED", "");
                        }

                        // Send the success page.  --Kris
                        context.Response = new uhttpsharp.HttpResponse(HttpResponseCode.Ok, Encoding.UTF8.GetBytes(html), false);
                    }

                    return(Task.Factory.GetCompleted());
                });

                HttpServer.Start();
            }
        }
Пример #2
0
 protected void RaiseAuthSuccess(IClientInfo client)
 {
     AuthSuccess?.Invoke(client);
 }
 protected void RaiseAuthSuccess()
 {
     AuthSuccess?.Invoke();
 }