private static void CreateAuthenticationCookieAndRedirect(bool setUserAuthenticated)
        {
            string     token  = null;
            HttpCookie cookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName];

            if (!string.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
            {
                token = HttpContext.Current.User.Identity.Name;
            }
            else if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
            {
                FormsAuthenticationTicket recTicket = FormsAuthentication.Decrypt(cookie.Value);
                token = recTicket.Name;
            }
            else if (setUserAuthenticated)
            {
                token = SessionManager.GetUserSessionGUID().ToString();
            }

            if (token != null)
            {
                var ticket = new FormsAuthenticationTicket(token, false, HttpContext.Current.Session.Timeout);

                string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }

            SessionManager.ExecuteCallback();
            SocialAuthUser.Redirect(GetCurrentConnectionToken().UserReturnURL);
        }
 protected void btnUpload_Click(object sender, EventArgs e)
 {
     SocialAuthUser sauser = new SocialAuthUser();
     MemoryStream ms = new MemoryStream(FileUpload1.FileBytes);
     IFormatter formatter = new BinaryFormatter();
     Token token = (Token)formatter.Deserialize(ms);
     sauser.LoadToken(token,"default.aspx");
 }
        protected void btn_Click(object sender, EventArgs e)
        {
            //We need to get user's selected provider enumerator.
            PROVIDER_TYPE selectedProvider = (PROVIDER_TYPE)Enum.Parse(typeof(PROVIDER_TYPE), ((Button)sender).Text.ToUpper());

            //Initialize User
            SocialAuthUser objUser = new SocialAuthUser(selectedProvider);

            //Call Login
            objUser.Login(returnUrl:"ManualLogin.aspx");
            //Login method also accepts a parameter for URL to which user should be redirected after login. If not specified,
            //automatically defaultUrl as set in Web.Config will be picked for redirection.
        }
        /// <summary>
        /// Redirects user to Login Screen based on authentication option chosen
        /// </summary>
        /// <param name="loginUrl"></param>
        internal static void RedirectToLoginPage(string loginUrl = "")
        {
            /***************LOGIC***************
             * If AuthenticationMode = SocialAuth
             *      and LoginUrl == empty, redirect to loginform.sauth
             *      and LoginUrl <> empty, redirect to LoginUrl
             * If AuthenticationMode = FormsAuthentication call RedirectToLoginPage()
             * If AuthenticationMode = Custom, redirect to Parameter passed in Login
             * ********************************/

            string loginUrlInConfigFile = Utility.GetSocialAuthConfiguration().Authentication.LoginUrl;
            string redirectTo           = "?ReturnUrl=" + HttpUtility.UrlEncode(HttpContext.Current.Request.Url.ToString());

            AUTHENTICATION_OPTION option = Utility.GetAuthenticationOption();

            //* If AuthenticationMode = SocialAuth and LoginUrl == empty, redirect to loginform.sauth
            if (option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_SOCIALAUTH_SCREEN)
            {
                SocialAuthUser.Redirect(HttpContext.Current.Request.GetBaseURL() + "socialauth/loginForm.sauth" + redirectTo);
            }

            //* If AuthenticationMode = SocialAuth and LoginUrl <> empty, redirect to LoginUrl
            else if (option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_CUSTOM_SCREEN)
            {
                SocialAuthUser.Redirect(HttpContext.Current.Request.GetBaseURL() + loginUrlInConfigFile + (redirectTo.EndsWith(loginUrlInConfigFile) ? "" : redirectTo));
            }

            //* If AuthenticationMode = FormsAuthentication call RedirectToLoginPage()
            else if (option == AUTHENTICATION_OPTION.FORMS_AUTHENTICATION)
            {
                FormsAuthentication.RedirectToLoginPage();
            }

            //* If AuthenticationMode = Custom, redirect to Configuration LoginURL OR otherwise SamePage as current request
            else if (option == AUTHENTICATION_OPTION.CUSTOM_SECURITY_CUSTOM_SCREEN)
            {
                if (string.IsNullOrEmpty(loginUrl))
                {
                    throw new Exception("Please specify Login URL");
                }
                else
                {
                    SocialAuthUser.Redirect(HttpContext.Current.Request.GetBaseURL() + loginUrl + redirectTo);
                }
            }
        }
示例#5
0
        public void LoadToken(Token token, string returnUrl)
        {
            // If expiresOn is specified and token has expired, refresh token!! Currently, exception thrown!
            if (token.ExpiresOn != null && token.ExpiresOn != DateTime.MinValue)
            {
                if (token.ExpiresOn < DateTime.Now)
                {
                    _logger.Error("Token has expired");
                    throw new OAuthException("Token has expired.");
                }
            }

            //If user is already connected with provider specified in token, ignore this request!
            if (SocialAuthUser.IsConnectedWith(token.Provider))
            {
                return;
            }

            //Load token
            token.UserReturnURL = returnUrl;
            SessionManager.AddConnectionToken(token);
            //SetUserAsLoggedIn();
        }
示例#6
0
        private void socialAuthLogin()
        {
            try
            {
                PROVIDER_TYPE selectedProvider = (PROVIDER_TYPE)Enum.Parse(typeof(PROVIDER_TYPE), context.Request["provider"].ToUpperInvariant());

                //Initialize User
                SocialAuthUser objUser = new SocialAuthUser(selectedProvider);

                //Call Login
                objUser.Login(returnUrl: "loginBySocialAuth.ashx");
            }
            catch (Exception ex)
            {
                context.Response.Write(ex.Message + (ex.InnerException != null ? " (" + ex.InnerException.Message + ")" : ""));
            }
        }
        /// <summary>
        /// Connects to a provider (Same as Login())
        /// </summary>
        /// <param name="providerType">Provider to which connection has to be established</param>
        /// <param name="returnURL">Optional URL where user will be redirected after login (for this provider only)</param>
        internal static void Connect(PROVIDER_TYPE providerType, string returnURL = "", string errorURL = "", bool skipRedirectionIfAlreadyConnected = false)
        {
            returnURL = returnURL ?? "";
            if (!returnURL.ToLower().StartsWith("http") && returnURL.Length > 0)
            {
                returnURL = HttpContext.Current.Request.GetBaseURL() + returnURL;
            }

            try
            {
                //User is already connected. return or redirect
                if (IsConnectedWith(providerType))
                {
                    if (skipRedirectionIfAlreadyConnected)
                    {
                        return;
                    }
                    else
                    {
                        if (Utility.GetAuthenticationMode() == System.Web.Configuration.AuthenticationMode.Forms)
                        {
                            returnURL = FormsAuthentication.DefaultUrl;
                            SocialAuthUser.Redirect(returnURL);
                        }
                    }
                    return;
                }

                AUTHENTICATION_OPTION option = Utility.GetAuthenticationOption();

                //Set where user should be redirected after successful login
                if (Utility.GetAuthenticationOption() == AUTHENTICATION_OPTION.CUSTOM_SECURITY_CUSTOM_SCREEN &&
                    string.IsNullOrEmpty(returnURL))
                {
                    throw new Exception("Please specify return URL");
                }
                else if (option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_CUSTOM_SCREEN || option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_SOCIALAUTH_SCREEN)
                {   //User has not specified and explicit return url. redirect to url from configuration
                    if (string.IsNullOrEmpty(returnURL))
                    {
                        returnURL = HttpContext.Current.Request.GetBaseURL() + Utility.GetSocialAuthConfiguration().Authentication.DefaultUrl;
                    }
                }

                //ReturnURL in request takes all priority
                if (HttpContext.Current.Request["ReturnUrl"] != null)
                {
                    string ret = HttpContext.Current.Request["ReturnUrl"];
                    if (Utility.GetAuthenticationOption() == AUTHENTICATION_OPTION.FORMS_AUTHENTICATION)
                    {
                        if (ret.ToLower().StartsWith(HttpContext.Current.Request.ApplicationPath.ToLower() + "/"))
                        {
                            ret = ret.Substring(ret.IndexOf("/", 1));
                            if (ret.StartsWith("/"))
                            {
                                ret = ret.Substring(1);
                            }
                        }
                    }
                    if (ret.ToLower().Contains("wa=wsignin"))
                    {
                        returnURL = HttpContext.Current.Request.GetBaseURL() + ret;
                    }
                    else if (!ret.ToLower().StartsWith("http"))
                    {
                        returnURL = HttpContext.Current.Request.GetBaseURL() + ret;
                    }
                    else
                    {
                        returnURL = ret;
                    }
                }

                SessionManager.InProgressToken = (new Token()
                {
                    Provider = providerType,
                    Domain = HttpContext.Current.Request.GetBaseURL(),
                    UserReturnURL = returnURL,
                    SessionGUID = SessionManager.GetUserSessionGUID(),
                    Profile = new UserProfile()
                    {
                        Provider = providerType
                    }
                });
                SessionManager.InProgressToken.Profile.Provider = providerType;
                if (!string.IsNullOrEmpty(errorURL))
                {
                    SessionManager.ErrorURL = HttpContext.Current.Request.GetBaseURL() + errorURL;
                }

                //CONNECT WITH PROVIDER
                var provider = ((IProviderConnect)ProviderFactory.GetProvider(providerType));
                provider.ConnectionToken = InProgressToken();
                provider.Connect();
            }
            catch
            {
                throw;
            }
        }