///<summary> /// Begin to authenticate current request synchronously. Returns <c>true</c> if the request is authenticated and <see cref="Session"/> is set; otherwise <c>false</c>. ///</summary> ///<param name="context">http context to authenticate.</param> ///<param name="cb">a callback to call upon operation is completed.</param> ///<param name="state">the user state to pass to the callback.</param> ///<exception cref="ArgumentNullException"><paramref name="context"/> is null.</exception> public IAsyncResult BeginAuthenticateRequest([NotNull] HttpContext context, [CanBeNull] AsyncCallback cb, [CanBeNull] object state) { if (context == null) throw FacebookApi.Nre("context"); bool saveSession = true; var tar = new TypedAsyncResult<bool>(cb, state); string code = context.Request.QueryString["code"]; if (!String.IsNullOrEmpty(code)) return BeginAuthenticate(code, GetCurrentUrl(context), tar.AsSafe(ar => { EndAuthenticate(ar); SaveSession(context); tar.Complete(IsAuthenticated, false); }), null); ISessionStorage ss = SessionStorage; if (ss != null) { _fbSession = ss.Session; if (_fbSession != null && !ss.IsSecure && _fbSession.Signature != GenerateSignature(_fbSession.ToJsonObject())) { _fbSession = null; } saveSession = _fbSession == null; } if (saveSession) SaveSession(context); tar.Complete(true); return tar; }
internal IAsyncResult BeginRequest( string url, HttpVerb httpVerb, Dictionary<string, string> args, AsyncCallback cb, object state) { if (args != null && args.Keys.Count > 0 && httpVerb == HttpVerb.Get) url = url+ (url.Contains("?") ? "&" : "?") + EncodeDictionary(args); var request = (HttpWebRequest)WebRequest.Create(url); request.Proxy = Proxy; request.Headers.Add(HttpRequestHeader.AcceptLanguage, Culture.IetfLanguageTag.ToLowerInvariant()); request.Method = httpVerb.ToString(); var tar = new TypedAsyncResult<ResponseData>(cb, state); Action beginGetResp = () => request.BeginGetResponse(tar.AsSafe(gr => { HttpWebResponse resp; Stream respStm; string contentType; try { resp = (HttpWebResponse)request.EndGetResponse(gr); contentType = ExtractContentType(resp); respStm = resp.GetResponseStream(); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { resp = (HttpWebResponse)ex.Response; contentType = ExtractContentType(resp); if (contentType == "text/javascript") { respStm = resp.GetResponseStream(); goto ok; } } throw TransportError(ex); } ok: var buf = new byte[4096]; var ms = new MemoryStream(buf.Length); AsyncCallback cbr = null; cbr = tar.AsSafe(br => { int cnt = respStm.EndRead(br); if (cnt == 0) { if (!tar.IsCompleted) { ((IDisposable)resp).Dispose(); ms.Seek(0, SeekOrigin.Begin); tar.Complete(new ResponseData { Json = Encoding.UTF8.GetString(ms.ToArray()), ContentType = contentType, }, false); } } else { ms.Write(buf, 0, cnt); respStm.BeginRead(buf, 0, buf.Length, cbr, null); } }, ex => ((IDisposable)resp).Dispose()); respStm.BeginRead(buf, 0, buf.Length, cbr, null); }), null); try { if (httpVerb == HttpVerb.Post) { string postData = EncodeDictionary(args); byte[] postDataBytes = Encoding.UTF8.GetBytes(postData); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postDataBytes.Length; request.BeginGetRequestStream(tar.AsSafe(rar => { Stream rqStm = request.EndGetRequestStream(rar); rqStm.BeginWrite(postDataBytes, 0, postDataBytes.Length, tar.AsSafe(wr => { rqStm.EndWrite(wr); beginGetResp(); }), null); }), null); } else { beginGetResp(); } } catch (Exception ex) { if (!tar.IsCompleted) tar.Complete(true, ex); } return tar; }
public void Init(HttpApplication app) { app.AddOnPostAcquireRequestStateAsync((s, e, cb, state) => { HttpContext context = app.Context; var tar = new TypedAsyncResult<Identity>(cb, state); if (context.Session == null || !context.Request.Url.AbsolutePath.Contains("/Connect")) { tar.Complete(true); return tar; } var util = new OAuthContext(AppId, AppSecret) { Culture = CultureInfo.CurrentCulture, ExProcessor = ex => Debug.Write(ex), }; util.SessionStorage = new AspNetSessionStore(context, util); util.BeginAuthenticateRequest(context, tar.AsSafe(ar => { util.EndAuthenticateRequest(ar); tar.Complete(new Identity(util), false); }), null); return tar; }, ar => { var ident = TypedAsyncResult<Identity>.End(ar, null); if (ident == null) return; HttpContext context = app.Context; if (!ident.IsAuthenticated) { //var @params = new Dictionary<string, string> { { "scope", "user_birthday" } }; context.Response.Redirect(ident.AuthContext.GetLoginUrl(context.Request.Url, new LoginParams { ReqPerms = "user_birthday" }), false); context.ApplicationInstance.CompleteRequest(); return; } context.User = new GenericPrincipal(ident, null); }); }