Exemple #1
0
        public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            try
            {
                var token = Auth(context, Scopes);

                if (token == null)
                {
                    throw new Exception("Login failed");
                }

                var loginProfile = GetLoginProfile(token.AccessToken);

                loginProfile.EMail = GetMail(token);

                return(loginProfile);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                return(LoginProfile.FromError(ex));
            }
        }
        public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            try
            {
                var token = Auth(context, Scopes, out var redirect);

                if (redirect)
                {
                    return(null);
                }

                if (token == null)
                {
                    throw new Exception("Login failed");
                }

                var uid = GetUid(token);

                return(RequestProfile(token.AccessToken, uid));
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                return(LoginProfile.FromError(Signature, InstanceCrypto, ex));
            }
        }
Exemple #3
0
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            if (!string.IsNullOrEmpty(context.Request["denied"]))
            {
                return(LoginProfile.FromError(new Exception("Canceled at provider")));
            }

            if (string.IsNullOrEmpty(context.Request["oauth_token"]))
            {
                var reqToken = OAuthUtility.GetRequestToken(TwitterKey, TwitterSecret, context.Request.GetUrlRewriter().AbsoluteUri);
                var url      = OAuthUtility.BuildAuthorizationUri(reqToken.Token).ToString();
                context.Response.Redirect(url, true);
                return(null);
            }

            var requestToken = context.Request["oauth_token"];
            var pin          = context.Request["oauth_verifier"];

            var tokens = OAuthUtility.GetAccessToken(TwitterKey, TwitterSecret, requestToken, pin);

            var accesstoken = new OAuthTokens
            {
                AccessToken       = tokens.Token,
                AccessTokenSecret = tokens.TokenSecret,
                ConsumerKey       = TwitterKey,
                ConsumerSecret    = TwitterSecret
            };

            var account = TwitterAccount.VerifyCredentials(accesstoken).ResponseObject;

            return(ProfileFromTwitter(account));
        }
Exemple #4
0
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            var token = context.Request["oauth_token"];

            if (string.IsNullOrEmpty(token))
            {
                var request = TwitterConsumer.StartSignInWithTwitter(TwitterSignIn, false);
                request.Send();
            }
            else
            {
                string screenName;
                int    userId;
                string accessToken;
                if (TwitterConsumer.TryFinishSignInWithTwitter(TwitterSignIn, out screenName, out userId, out accessToken))
                {
                    //Sucess. Get information
                    var info    = TwitterConsumer.GetUserInfo(TwitterSignIn, userId, accessToken);
                    var profile = ProfileFromTwitter(info);
                    return(profile);
                }
                return(LoginProfile.FromError(new Exception("Login failed")));
            }


            return(null);
        }
        public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            try
            {
                var token = Auth(context, Scopes, out var redirect, context.Request.Query["access_type"] == "offline"
                                                      ? new Dictionary <string, string>
                {
                    { "force_confirm", "true" }
                }
                                                      : null);
                if (redirect)
                {
                    return(null);
                }

                return(GetLoginProfile(token?.AccessToken));
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                return(LoginProfile.FromError(Signature, InstanceCrypto, ex));
            }
        }
        public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            try
            {
                var token = Auth(context, Scopes, (context.Request["access_type"] ?? "") == "offline"
                                                      ? new Dictionary <string, string>
                {
                    { "revoke", "1" }
                }
                                                      : null);

                if (token == null)
                {
                    throw new Exception("Login failed");
                }

                var loginProfile = GetLoginProfile(token.AccessToken);

                loginProfile.EMail = GetMail(token);

                return(loginProfile);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                return(LoginProfile.FromError(ex));
            }
        }
Exemple #7
0
        //<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        //<person>
        //  <id>FQJIJg-u80</id>
        //  <first-name>alexander</first-name>
        //  <last-name>rusanov</last-name>
        //</person>

        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            var token = context.Request["oauth_token"];

            if (string.IsNullOrEmpty(token))
            {
                LinkedInConsumer.RequestAuthorization(SignIn);
            }
            else
            {
                var accessTokenResponse = SignIn.ProcessUserAuthorization();
                if (accessTokenResponse != null)
                {
                    //All ok. request info
                    var responce = LinkedInConsumer.GetProfile(SignIn, accessTokenResponse.AccessToken);
                    var document = XDocument.Parse(responce).CreateNavigator();
                    return(new LoginProfile()
                    {
                        Id = document.SelectNodeValue("//id"),
                        FirstName = document.SelectNodeValue("//first-name"),
                        LastName = document.SelectNodeValue("//last-name"),
                        Avatar = document.SelectNodeValue("//picture-url"),
                        Provider = ProviderConstants.LinkedIn
                    });
                }
                return(LoginProfile.FromError(new Exception("Login failed")));
            }
            return(null);
        }
 public LoginProfile GetLoginProfile(string accessToken)
 {
     try
     {
         return(RequestProfile(accessToken));
     }
     catch (Exception ex)
     {
         return(LoginProfile.FromError(ex));
     }
 }
Exemple #9
0
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            var error = context.Request["error"];

            if (!string.IsNullOrEmpty(error))
            {
                if (error == "access_denied")
                {
                    error = "Canceled at provider";
                }
                return(LoginProfile.FromError(new Exception(error)));
            }

            var code = context.Request["code"];

            if (string.IsNullOrEmpty(code))
            {
                var scope = "https://www.googleapis.com/auth/userinfo.email";
                if (@params.ContainsKey("scope"))
                {
                    scope = @params["scope"];
                }
                //"https://www.googleapis.com/auth/drive"

                var getCodeUrl =
                    string.Format(GoogleOauthUrl + "auth?response_type=code&client_id={0}&redirect_uri={1}&scope={2}&state={3}",
                                  GoogleOAuth20ClientId,
                                  GoogleOAuth20RedirectUrl,
                                  scope,
                                  HttpUtility.UrlEncode(context.Request.Url.ToString()));

                context.Response.Redirect(getCodeUrl, true);
            }
            else
            {
                try
                {
                    var token = OAuth20TokenHelper.GetAccessToken(GoogleOauthUrl + "token", GoogleOAuth20ClientId, GoogleOAuth20ClientSecret, GoogleOAuth20RedirectUrl, code);

                    var googleProfile = RequestHelper.PerformRequest(GoogleProfileUrl + "me", headers: new Dictionary <string, string> {
                        { "Authorization", "Bearer " + token.AccessToken }
                    });
                    var loginProfile = ProfileFromGoogle(googleProfile);
                    return(loginProfile);
                }
                catch (Exception ex)
                {
                    return(LoginProfile.FromError(ex));
                }
            }

            return(null);
        }
Exemple #10
0
        public async Task Invoke(HttpContext context)
        {
            var scope = context.PushRewritenUri();

            if (string.IsNullOrEmpty(context.Request.Query["p"]))
            {
                _params = new Dictionary <string, string>(context.Request.Query.Count);
                //Form params and redirect
                foreach (var key in context.Request.Query.Keys)
                {
                    _params.Add(key, context.Request.Query[key]);
                }

                //Pack and redirect
                var uriBuilder = new UriBuilder(context.Request.GetUrlRewriter());
                var token      = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(_params)));
                uriBuilder.Query = "p=" + token;
                context.Response.Redirect(uriBuilder.Uri.ToString(), true);
                await context.Response.CompleteAsync();

                return;
            }
            else
            {
                _params = JsonSerializer.Deserialize <Dictionary <string, string> >(Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(context.Request.Query["p"])));
            }

            if (!string.IsNullOrEmpty(Auth))
            {
                try
                {
                    var profile = ProviderManager.Process(Auth, context, _params);
                    if (profile != null)
                    {
                        await SendClientData(context, profile);
                    }
                }
                catch (ThreadAbortException)
                {
                    //Thats is responce ending
                }
                catch (Exception ex)
                {
                    await SendClientData(context, LoginProfile.FromError(Signature, InstanceCrypto, ex));
                }
            }
            else
            {
                //Render xrds
                await RenderXrds(context);
            }
            context.PopRewritenUri();
        }
Exemple #11
0
        public void ProcessRequest(HttpContext context)
        {
            context.PushRewritenUri();

            if (string.IsNullOrEmpty(context.Request["p"]))
            {
                _params = new Dictionary <string, string>(context.Request.QueryString.Count);
                //Form params and redirect
                foreach (var key in context.Request.QueryString.AllKeys)
                {
                    _params.Add(key, context.Request.QueryString[key]);
                }

                //Pack and redirect
                var uriBuilder = new UriBuilder(context.Request.GetUrlRewriter());
                var token      = HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(_params)));
                uriBuilder.Query = "p=" + token;
                context.Response.Redirect(uriBuilder.Uri.ToString(), true);
            }
            else
            {
                _params = ((Dictionary <string, object>) new JavaScriptSerializer().DeserializeObject(
                               Encoding.UTF8.GetString(HttpServerUtility.UrlTokenDecode(context.Request["p"])))).ToDictionary(x => x.Key, y => (string)y.Value);
            }


            if (!string.IsNullOrEmpty(Auth))
            {
                try
                {
                    var profile = ProviderManager.Process(Auth, context, _params);
                    if (profile != null)
                    {
                        SendClientData(context, profile);
                    }
                }
                catch (ThreadAbortException)
                {
                    //Thats is responce ending
                }
                catch (Exception ex)
                {
                    SendClientData(context, LoginProfile.FromError(ex));
                }
            }
            else
            {
                //Render xrds
                RenderXrds(context);
            }
            context.PopRewritenUri();
        }
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            var builder = new UriBuilder(context.Request.GetUrlRewriter())
            {
                Query = "p=" + context.Request["p"]
            };
            var oauth = new FacebookOAuthClient
            {
                AppId       = KeyStorage.Get("facebookAppID"),
                AppSecret   = KeyStorage.Get("facebookAppSecret"),
                RedirectUri = builder.Uri
            };
            FacebookOAuthResult result;

            if (FacebookOAuthResult.TryParse(context.Request.GetUrlRewriter(), out result))
            {
                if (result.IsSuccess)
                {
                    var accessToken = (Facebook.JsonObject)oauth.ExchangeCodeForAccessToken(result.Code);
                    var request     = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString((string)accessToken["access_token"]));
                    using (var response = request.GetResponse())
                    {
                        using (var responseStream = response.GetResponseStream())
                        {
                            var graph   = FacebookGraph.Deserialize(responseStream);
                            var profile = ProfileFromFacebook(graph);
                            return(profile);
                        }
                    }
                }
                return(LoginProfile.FromError(new Exception(result.ErrorReason)));
            }
            //Maybe we didn't query
            var extendedPermissions = new[] { "email", "user_about_me" };
            var parameters          = new Dictionary <string, object>
            {
                { "display", "popup" }
            };

            if (extendedPermissions.Length > 0)
            {
                var scope = new StringBuilder();
                scope.Append(string.Join(",", extendedPermissions));
                parameters["scope"] = scope.ToString();
            }
            var loginUrl = oauth.GetLoginUrl(parameters);

            context.Response.Redirect(loginUrl.ToString());
            return(LoginProfile.FromError(new Exception("Failed to login with facebook")));
        }
        public static LoginProfile GetLoginProfile(string providerType, string accessToken)
        {
            if (!Providers.Keys.Contains(providerType))
            {
                throw new ArgumentException("Unknown provider type", "providerType");
            }

            try
            {
                return(Providers[providerType].GetLoginProfile(accessToken));
            }
            catch (Exception ex)
            {
                return(LoginProfile.FromError(ex));
            }
        }
Exemple #14
0
 public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
 {
     try
     {
         var token = Auth(context, GoogleProfileScope);
         return(RequestProfile(token));
     }
     catch (ThreadAbortException)
     {
         throw;
     }
     catch (Exception ex)
     {
         return(LoginProfile.FromError(ex));
     }
 }
        public virtual LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            try
            {
                var token = Auth(context, Scopes);

                return(GetLoginProfile(token?.AccessToken));
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                return(LoginProfile.FromError(Signature, InstanceCrypto, ex));
            }
        }
 public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
 {
     try
     {
         var token  = Auth(context, Scopes);
         var claims = ValidateIdToken(JObject.Parse(token.OriginJson).Value <string>("id_token"));
         return(GetProfileFromClaims(claims));
     }
     catch (ThreadAbortException)
     {
         throw;
     }
     catch (Exception ex)
     {
         return(LoginProfile.FromError(ex));
     }
 }
Exemple #17
0
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            try
            {
                var token = Auth(context, LinkedInProfileScope);

                return(GetLoginProfile(token == null ? null : token.AccessToken));
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                return(LoginProfile.FromError(ex));
            }
        }
 public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
 {
     try
     {
         var token = Auth(context, FacebookProfileScope);
         return(token == null
                    ? LoginProfile.FromError(new Exception("Login failed"))
                    : RequestProfile(token.AccessToken));
     }
     catch (ThreadAbortException)
     {
         throw;
     }
     catch (Exception ex)
     {
         return(LoginProfile.FromError(ex));
     }
 }
Exemple #19
0
        public static LoginProfile GetLoginProfile(string providerType, string accessToken, Signature signature, InstanceCrypto instanceCrypto)
        {
            var consumer = GetLoginProvider(providerType, signature, instanceCrypto);

            if (consumer == null)
            {
                throw new ArgumentException("Unknown provider type", "providerType");
            }

            try
            {
                return(consumer.GetLoginProfile(accessToken));
            }
            catch (Exception ex)
            {
                return(LoginProfile.FromError(signature, instanceCrypto, ex));
            }
        }
Exemple #20
0
        public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            try
            {
                var token = Auth(context, Scopes);

                if (token == null)
                {
                    throw new Exception("Login failed");
                }

                return(GetLoginProfile(token.AccessToken));
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                return(LoginProfile.FromError(Signature, InstanceCrypto, ex));
            }
        }
        public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            try
            {
                var token = Auth(context, Scopes, (context.Request["access_type"] ?? "") == "offline"
                                                      ? new Dictionary <string, string>
                {
                    { "force_confirm", "true" }
                }
                                                      : null);

                return(GetLoginProfile(token == null ? null : token.AccessToken));
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                return(LoginProfile.FromError(ex));
            }
        }
        public virtual LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params, IDictionary <string, string> additionalStateArgs = null)
        {
            try
            {
                var token = Auth(context, Scopes, out var redirect, @params, additionalStateArgs);

                if (redirect)
                {
                    return(null);
                }

                return(GetLoginProfile(token?.AccessToken));
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                return(LoginProfile.FromError(Signature, InstanceCrypto, ex));
            }
        }
        public static LoginProfile GetLoginProfile(string providerType, string accessToken = null, string codeOAuth = null)
        {
            var consumer = GetLoginProvider(providerType);

            if (consumer == null)
            {
                throw new ArgumentException("Unknown provider type", "providerType");
            }

            try
            {
                if (accessToken == null && codeOAuth != null)
                {
                    return(consumer.GetLoginProfile(consumer.GetToken(codeOAuth)));
                }

                return(consumer.GetLoginProfile(accessToken));
            }
            catch (Exception ex)
            {
                return(LoginProfile.FromError(ex));
            }
        }
Exemple #24
0
        public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params, IDictionary <string, string> additionalStateArgs = null)
        {
            try
            {
                var token = Auth(context, Scopes, out var redirect, context.Request.Query["access_type"] == "offline"
                                      ? new Dictionary <string, string>
                {
                    { "revoke", "1" }
                }
                                      : null, additionalStateArgs);

                if (redirect)
                {
                    return(null);
                }

                if (token == null)
                {
                    throw new Exception("Login failed");
                }

                var loginProfile = GetLoginProfile(token.AccessToken);

                loginProfile.EMail = GetMail(token);

                return(loginProfile);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                return(LoginProfile.FromError(Signature, InstanceCrypto, ex));
            }
        }
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            var token = context.Request["oauth_token"];

            if (string.IsNullOrEmpty(token))
            {
                LinkedInConsumer.RequestAuthorization(SignIn);
            }
            else
            {
                var accessTokenResponse = SignIn.ProcessUserAuthorization();
                try
                {
                    return(token == null
                               ? LoginProfile.FromError(new Exception("Login failed"))
                               : RequestProfile(accessTokenResponse.AccessToken));
                }
                catch (Exception ex)
                {
                    return(LoginProfile.FromError(ex));
                }
            }
            return(null);
        }
Exemple #26
0
        public async Task Invoke(HttpContext context)
        {
            _ = context.PushRewritenUri();

            if (string.IsNullOrEmpty(context.Request.Query["p"]))
            {
                _params = new Dictionary <string, string>(context.Request.Query.Count);
                //Form params and redirect
                foreach (var key in context.Request.Query.Keys)
                {
                    _params.Add(key, context.Request.Query[key]);
                }

                //Pack and redirect
                var uriBuilder = new UriBuilder(context.Request.GetUrlRewriter());
                var token      = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(_params)));
                uriBuilder.Query = "p=" + token;
                context.Response.Redirect(uriBuilder.Uri.ToString(), true);
                await context.Response.CompleteAsync();

                return;
            }
            else
            {
                _params = JsonSerializer.Deserialize <Dictionary <string, string> >(Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(context.Request.Query["p"])));
            }

            if (!string.IsNullOrEmpty(Auth))
            {
                try
                {
                    var desktop = _params.ContainsKey("desktop") && _params["desktop"] == "true";
                    IDictionary <string, string> additionalStateArgs = null;

                    if (desktop)
                    {
                        additionalStateArgs = context.Request.Query.ToDictionary(r => r.Key, r => r.Value.FirstOrDefault());
                        if (!additionalStateArgs.ContainsKey("desktop"))
                        {
                            additionalStateArgs.Add("desktop", "true");
                        }
                    }

                    var profile = ProviderManager.Process(Auth, context, null, additionalStateArgs);
                    if (profile != null)
                    {
                        await SendJsCallback(context, profile);
                    }
                }
                catch (ThreadAbortException)
                {
                    //Thats is responce ending
                }
                catch (Exception ex)
                {
                    await SendJsCallback(context, LoginProfile.FromError(Signature, InstanceCrypto, ex));
                }
            }
            else
            {
                //Render xrds
                await RenderXrds(context);
            }
            context.PopRewritenUri();
        }
Exemple #27
0
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params)
        {
            var builder = new UriBuilder(context.Request.GetUrlRewriter()) {Query = "p=" + context.Request["p"]};
            var oauth = new FacebookOAuthClient
            {
                AppId = KeyStorage.Get("facebookAppID"),
                AppSecret = KeyStorage.Get("facebookAppSecret"),
                RedirectUri = builder.Uri
            };
            FacebookOAuthResult result;
            if (FacebookOAuthResult.TryParse(context.Request.GetUrlRewriter(), out result))
            {
                if (result.IsSuccess)
                {
                    var accessToken = (Facebook.JsonObject)oauth.ExchangeCodeForAccessToken(result.Code);
                    var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString((string)accessToken["access_token"]));
                    using (var response = request.GetResponse())
                    {
                        using (var responseStream = response.GetResponseStream())
                        {
                            var graph = FacebookGraph.Deserialize(responseStream);
                            var profile = ProfileFromFacebook(graph);
                            return profile;
                        }
                    }
                }
                return LoginProfile.FromError(new Exception(result.ErrorReason));
            }
            //Maybe we didn't query
            var extendedPermissions = new[] { "email", "user_about_me" };
            var parameters = new Dictionary<string, object>
                                 {
                                     { "display", "popup" }
                                 };

            if (extendedPermissions.Length > 0)
            {
                var scope = new StringBuilder();
                scope.Append(string.Join(",", extendedPermissions));
                parameters["scope"] = scope.ToString();
            }
            var loginUrl = oauth.GetLoginUrl(parameters);
            context.Response.Redirect(loginUrl.ToString());
            return LoginProfile.FromError(new Exception("Failed to login with facebook"));




            //var client = new FacebookClient
            //                 {
            //                     ClientIdentifier = KeyStorage.Get("facebookAppID"),
            //                     ClientSecret = KeyStorage.Get("facebookAppSecret"),
            //                 };
            //try
            //{
            //    IAuthorizationState authorization = client.ProcessUserAuthorization(new HttpRequestInfo(context.Request));
            //    if (authorization == null)
            //    {
            //        // Kick off authorization request
            //        var scope = new List<string>()
            //                    {
            //                        "email,user_about_me",
            //                    };
            //        client.RequestUserAuthorization(scope, null, null);
            //    }
            //    else
            //    {
            //        var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
            //        using (var response = request.GetResponse())
            //        {
            //            if (response != null)
            //                using (var responseStream = response.GetResponseStream())
            //                {
            //                    var graph = FacebookGraph.Deserialize(responseStream);
            //                    var profile = ProfileFromFacebook(graph);
            //                    return profile;
            //                }
            //        }
            //    }
            //}
            //catch (ProtocolException e)
            //{
            //    if (e.InnerException is WebException)
            //    {
            //        //Read stream
            //        var responce =
            //            new StreamReader((e.InnerException as WebException).Response.GetResponseStream()).ReadToEnd();
            //    }
            //    throw;
            //}

        }
Exemple #28
0
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            var response = Openid.GetResponse();

            if (response == null)
            {
                Identifier id;
                if (Identifier.TryParse(@params["oid"], out id))
                {
                    try
                    {
                        IAuthenticationRequest request;

                        var realmUrlString = String.Empty;

                        if (@params.ContainsKey("realmUrl"))
                        {
                            realmUrlString = @params["realmUrl"];
                        }

                        if (!String.IsNullOrEmpty(realmUrlString))
                        {
                            request = Openid.CreateRequest(id, new Realm(realmUrlString));
                        }
                        else
                        {
                            request = Openid.CreateRequest(id);
                        }

                        request.AddExtension(new ClaimsRequest
                        {
                            Email      = DemandLevel.Require,
                            Nickname   = DemandLevel.Require,
                            Country    = DemandLevel.Request,
                            Gender     = DemandLevel.Request,
                            PostalCode = DemandLevel.Request,
                            TimeZone   = DemandLevel.Request,
                            FullName   = DemandLevel.Request,
                        });
                        var fetch = new FetchRequest();
                        fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                        //Duplicating attributes
                        fetch.Attributes.AddRequired("http://schema.openid.net/contact/email");//Add two more
                        fetch.Attributes.AddRequired("http://openid.net/schema/contact/email");
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Alias);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Media.Images.Default);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Middle);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Person.Gender);
                        fetch.Attributes.AddRequired(WellKnownAttributes.BirthDate.WholeBirthDate);
                        request.AddExtension(fetch);
                        request.RedirectToProvider();
                        context.Response.End();//This will throw thread abort
                    }
                    catch (ProtocolException ex)
                    {
                        return(LoginProfile.FromError(ex));
                    }
                }
                else
                {
                    return(LoginProfile.FromError(new Exception("invalid OpenID identifier")));
                }
            }
            else
            {
                // Stage 3: OpenID Provider sending assertion response
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    var spprofile    = response.GetExtension <ClaimsResponse>();
                    var fetchprofile = response.GetExtension <FetchResponse>();

                    var realmUrlString = String.Empty;
                    if (@params.ContainsKey("realmUrl"))
                    {
                        realmUrlString = @params["realmUrl"];
                    }

                    var profile = ProfileFromOpenId(spprofile, fetchprofile, response.ClaimedIdentifier.ToString(), realmUrlString);
                    return(profile);

                case AuthenticationStatus.Canceled:
                    return(LoginProfile.FromError(new Exception("Canceled at provider")));

                case AuthenticationStatus.Failed:
                    return(LoginProfile.FromError(response.Exception));
                }
            }
            return(null);
        }
        public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            if (!string.IsNullOrEmpty(context.Request["denied"]))
            {
                return(LoginProfile.FromError(new Exception("Canceled at provider")));
            }

            var appClient = new TwitterClient(TwitterKey, TwitterSecret);

            if (string.IsNullOrEmpty(context.Request["oauth_token"]))
            {
                var callbackAddress = new UriBuilder(RedirectUri)
                {
                    Query = "state=" + HttpUtility.UrlEncode(context.Request.GetUrlRewriter().AbsoluteUri)
                };

                var authenticationRequestId = Guid.NewGuid().ToString();

                // Add the user identifier as a query parameters that will be received by `ValidateTwitterAuth`
                var redirectURL = _myAuthRequestStore.AppendAuthenticationRequestIdToCallbackUrl(callbackAddress.ToString(), authenticationRequestId);

                // Initialize the authentication process
                var authenticationRequestToken = appClient.Auth.RequestAuthenticationUrlAsync(redirectURL)
                                                 .ConfigureAwait(false)
                                                 .GetAwaiter()
                                                 .GetResult();

                // Store the token information in the store
                _myAuthRequestStore.AddAuthenticationTokenAsync(authenticationRequestId, authenticationRequestToken)
                .ConfigureAwait(false)
                .GetAwaiter()
                .GetResult();

                context.Response.Redirect(authenticationRequestToken.AuthorizationURL, true);

                return(null);
            }

            // Extract the information from the redirection url
            var requestParameters = RequestCredentialsParameters.FromCallbackUrlAsync(context.Request.RawUrl, _myAuthRequestStore).GetAwaiter().GetResult();
            // Request Twitter to generate the credentials.
            var userCreds = appClient.Auth.RequestCredentialsAsync(requestParameters)
                            .ConfigureAwait(false)
                            .GetAwaiter()
                            .GetResult();

            // Congratulations the user is now authenticated!
            var userClient = new TwitterClient(userCreds);

            var user = userClient.Users.GetAuthenticatedUserAsync()
                       .ConfigureAwait(false)
                       .GetAwaiter()
                       .GetResult();

            var userSettings = userClient.AccountSettings.GetAccountSettingsAsync()
                               .ConfigureAwait(false)
                               .GetAwaiter()
                               .GetResult();

            return(user == null
                       ? null
                       : new LoginProfile
            {
                Name = user.Name,
                DisplayName = user.ScreenName,
                Avatar = user.ProfileImageUrl,
                Locale = userSettings.Language.ToString(),
                Id = user.Id.ToString(CultureInfo.InvariantCulture),
                Provider = ProviderConstants.Twitter
            });
        }