/// <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); } } }
//------------ Getting & Checking Connections /// <summary> /// Returns an instance of SocialAuthUser with current connection /// </summary> /// <returns></returns> public static SocialAuthUser GetCurrentUser() { AUTHENTICATION_OPTION option = Utility.GetAuthenticationOption(); if (SessionManager.ConnectionsCount == 0) { if (option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_CUSTOM_SCREEN || option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_SOCIALAUTH_SCREEN) { RedirectToLoginPage(); } else { return(new SocialAuthUser() { contextToken = new Token() }); } } return(new SocialAuthUser() { contextToken = GetCurrentConnectionToken() }); }
internal static AUTHENTICATION_OPTION GetAuthenticationOption() { AUTHENTICATION_OPTION option = AUTHENTICATION_OPTION.NOT_SUPPORTED; AuthenticationMode mode = GetAuthenticationMode(); if (mode == AuthenticationMode.None || mode == AuthenticationMode.Windows) { mode = AuthenticationMode.None; } if (mode == AuthenticationMode.Forms) { option = AUTHENTICATION_OPTION.FORMS_AUTHENTICATION; } else if (mode == AuthenticationMode.None && GetSocialAuthConfiguration().Authentication.Enabled) { if (String.IsNullOrEmpty(GetSocialAuthConfiguration().Authentication.LoginUrl)) { option = AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_SOCIALAUTH_SCREEN; } else { option = AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_CUSTOM_SCREEN; } } else if (mode == AuthenticationMode.None && !GetSocialAuthConfiguration().Authentication.Enabled) { option = AUTHENTICATION_OPTION.CUSTOM_SECURITY_CUSTOM_SCREEN; } if (option == AUTHENTICATION_OPTION.NOT_SUPPORTED) { throw new Exception("invalid authentication type."); } return(option); }
/// <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; } }
protected void context_PreRequestHandlerExecute(object sender, EventArgs e) { /************************* * If Request is of type .sauth OR any type as specified in Config, allow and skip. * If Request is of LoginURL, skip * OTHERWISE::::::::::::::::::::: * <<<<IF USER IS NOT LOGGED IN>>> * If AuthenticationOption = SocialAuth * Redirect in Priority - ConfigurationLoginURL, "LoginForm.sauth" * If AuthenticationOption = FormsAuthentication * Don't do anything. Let .NET handle it as per user's setting in Web.Config * If AuthenticationOption = Everything Custom * Don't do anything. User will put checking code on every page himself. * **********************/ AUTHENTICATION_OPTION option = Utility.GetAuthenticationOption(); if (option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_CUSTOM_SCREEN || option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_SOCIALAUTH_SCREEN) { //block any .aspx page. Rest all is allowed. //TODO: Better Implementation of this string requestUrlExtension = VirtualPathUtility.GetExtension(HttpContext.Current.Request.RawUrl); string urlWithoutParameters = (new Uri(HttpContext.Current.Request.Url.ToString()).GetLeftPart(UriPartial.Path)).ToLower(); string host = (new Uri(HttpContext.Current.Request.GetBaseURL())).ToString().ToLower(); if (requestUrlExtension != ".aspx" && !string.IsNullOrEmpty(requestUrlExtension)) { return; } //Check for excludes //Allowed Folders if (!string.IsNullOrEmpty(Utility.GetSocialAuthConfiguration().Allow.Folders)) { string[] foldersToExclude = Utility.GetSocialAuthConfiguration().Allow.Folders.Split(new char[] { '|' }); foreach (string folderName in foldersToExclude) { if (urlWithoutParameters.Contains(host + (host.EndsWith("/") ? "" : "/") + folderName)) { return; } } } //Allowed Files if (!string.IsNullOrEmpty(Utility.GetSocialAuthConfiguration().Allow.Files)) { string[] filesToExclude = Utility.GetSocialAuthConfiguration().Allow.Files.Split(new char[] { '|' }); foreach (string fileName in filesToExclude) { if (Regex.IsMatch(urlWithoutParameters, "/" + fileName.ToLower() + "$")) { return; } } } //If requested page is login URL only, allow it string currentUrl = HttpContext.Current.Request.Url.AbsolutePath; string loginurl = Utility.GetSocialAuthConfiguration().Authentication.LoginUrl; loginurl = string.IsNullOrEmpty(loginurl) ? "socialauth/loginform.sauth" : loginurl; if (currentUrl.ToLower().EndsWith(loginurl.ToLower())) { return; } //If Url is pointing to a .aspx page, authorize it! HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); if (cookie != null) { HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(FormsAuthentication.Decrypt(cookie.Value)), null); } else { //User is not logged in SocialAuthUser.RedirectToLoginPage(); } if (HttpContext.Current.Session != null) { if (SocialAuthUser.IsLoggedIn() && HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] == null) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(SessionManager.GetUserSessionGUID().ToString(), false, HttpContext.Current.Session.Timeout); string EncryptedTicket = FormsAuthentication.Encrypt(ticket); cookie = new HttpCookie(FormsAuthentication.FormsCookieName, EncryptedTicket); HttpContext.Current.Response.Cookies.Add(cookie); } } } //Often, Forms Cookie persist even where there is no connection. To avoid that!! if (HttpContext.Current.Session != null) { if (SessionManager.ConnectionsCount == 0) { if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] != null && Utility.GetAuthenticationOption() != AUTHENTICATION_OPTION.FORMS_AUTHENTICATION) { if (SessionManager.GetUserSessionGUID().ToString() != FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name) { SocialAuthUser.Disconnect(); } } } } if (HttpContext.Current.ApplicationInstance.IsSTSaware()) { if (HttpContext.Current.Session != null) { if (SocialAuthUser.IsLoggedIn()) { if (SocialAuthUser.GetCurrentUser().GetProfile() != null) { SocialAuthUser.SetClaims(); } } } } }