protected void Page_Load(object sender, EventArgs e)
 {
     if (SocialAuthUser.IsLoggedIn())
     {
         lbtnLogout.Visible = true;
     }
 }
Example #2
0
 public static string IsUserLoggedIn()
 {
     try
     {
         return(SocialAuthUser.IsLoggedIn().ToString());
     }
     catch
     {
         return("error");
     }
 }
 public static string GetProvider(this IIdentity identity)
 {
     if (SocialAuthUser.IsLoggedIn() && Brickred.SocialAuth.NET.Core.Utility.GetSocialAuthConfiguration().Authentication.AllowModificationToUserIdentity)
     {
         return(SocialAuthUser.CurrentConnection.ProviderType.ToString());
     }
     else
     {
         return("");
     }
 }
 public static List <Brickred.SocialAuth.NET.Core.BusinessObjects.Contact> GetContacts(this IIdentity identity)
 {
     if (SocialAuthUser.IsLoggedIn() && Brickred.SocialAuth.NET.Core.Utility.GetSocialAuthConfiguration().Authentication.AllowModificationToUserIdentity)
     {
         return(SocialAuthUser.GetCurrentUser().GetContacts());
     }
     else
     {
         return(null);
     }
 }
    /// <summary>
    /// This method returns the claims to be issued in the token.
    /// </summary>
    /// <param name="principal">The caller's principal.</param>
    /// <param name="request">The incoming RST, can be used to obtain addtional information.</param>
    /// <param name="scope">The scope information corresponding to this request.</param>
    /// <exception cref="ArgumentNullException">If 'principal' parameter is null.</exception>
    /// <returns>The outgoing claimsIdentity to be included in the issued token.</returns>
    protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal,
                                                               RequestSecurityToken request, Scope scope)
    {
        if (null == principal)
        {
            throw new ArgumentNullException("principal");
        }

        ClaimsIdentity outputIdentity = new ClaimsIdentity();

        // Issue custom claims.
        // TODO: Change the claims below to issue custom claims
        // that are required by your application.
        // Update the application's configuration file to reflect
        // the new claims requirements.

        // outputIdentity.Claims.Add( new Claim(System.IdentityModel.Claims.ClaimTypes.Name, principal.Identity.Name ) );
        // outputIdentity.Claims.Add( new Claim( ClaimTypes.Role, "Manager" ) );

        // The Wingtip implementation.
        string       username = principal.Identity.Name;
        List <Claim> claims   = new List <Claim>();

        if (SocialAuthUser.IsLoggedIn())
        {
            claims = UserInfo.GetClaimsForSocialAuthUser(SocialAuthUser.GetCurrentUser().GetProfile());
        }
        else
        {
            claims = UserInfo.GetClaimsForUser(username);
        }
        foreach (Claim claim in claims)
        {
            outputIdentity.Claims.Add(claim);
        }

        return(outputIdentity);
    }
    /// <summary>
    /// Performs WS-Federation Passive Protocol processing.
    /// </summary>
    protected void Page_PreRender(object sender, EventArgs e)
    {
        string action = Request.QueryString[WSFederationConstants.Parameters.Action];

        try
        {
            if (action == WSFederationConstants.Actions.SignIn)
            {
                // Process signin request.
                SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
                if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
                {
                    SecurityTokenService  sts             = new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current);
                    SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User, sts);
                    FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, Response);
                }
                else
                {
                    throw new UnauthorizedAccessException();
                }
            }
            else if (action == WSFederationConstants.Actions.SignOut)
            {
                // Process signout request.
                SignOutRequestMessage requestMessage = (SignOutRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
                FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest(requestMessage, User, requestMessage.Reply, Response);
            }
            else if (action == null && SocialAuthUser.IsLoggedIn())
            {
                string originalUrl = SocialAuthUser.GetCurrentUser().GetConnection(SocialAuthUser.CurrentProvider).GetConnectionToken().UserReturnURL;

                //replace ru value
                int    wctxBeginsFrom = originalUrl.IndexOf("wctx=");
                int    wctxEndsAt     = originalUrl.IndexOf("&wct=");
                string wctxContent    = originalUrl.Substring(wctxBeginsFrom + 5, wctxEndsAt - (wctxBeginsFrom + 5));
                originalUrl = originalUrl.Replace(wctxContent, Server.UrlEncode(wctxContent));

                //replace wtrealm value
                int    wtrealmBeginsFrom = originalUrl.IndexOf("wtrealm=");
                int    wtrealmEndsAt     = originalUrl.IndexOf("&", wtrealmBeginsFrom);
                string wtrealmContent    = originalUrl.Substring(wtrealmBeginsFrom + 8, wtrealmEndsAt - (wtrealmBeginsFrom + 8));
                originalUrl = originalUrl.Replace(wtrealmContent, Server.UrlEncode(wtrealmContent));

                SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(new Uri(originalUrl));
                if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
                {
                    SecurityTokenService  sts             = new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current);
                    SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User, sts);
                    FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, Response);
                }
            }
            else
            {
                throw new InvalidOperationException(
                          String.Format(CultureInfo.InvariantCulture,
                                        "The action '{0}' (Request.QueryString['{1}']) is unexpected. Expected actions are: '{2}' or '{3}'.",
                                        String.IsNullOrEmpty(action) ? "<EMPTY>" : action,
                                        WSFederationConstants.Parameters.Action,
                                        WSFederationConstants.Actions.SignIn,
                                        WSFederationConstants.Actions.SignOut));
            }
        }
        catch (Exception exception)
        {
            throw new Exception("An unexpected error occurred when processing the request. See inner exception for details.", exception);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //Required to be done when using custom mode
        //if (!SocialAuthUser.IsLoggedIn())
        //    SocialAuthUser.RedirectToLoginPage("ManualLogin.aspx");


        foreach (PROVIDER_TYPE p in SocialAuthUser.GetConnectedProviders())
        {
            divConnections.Controls.Add(new Literal()
            {
                Text = "<br>Connected to: <b>" + p.ToString() + "</b> with identifier <b>" +
                       SocialAuthUser.GetCurrentUser().GetProfile(p).GetIdentifier() + "</b>"
            });
            LinkButton logoutBtn = new LinkButton()
            {
                Text = "[Logout from " + p.ToString() + "]", CommandArgument = p.ToString()
            };
            logoutBtn.Command += new CommandEventHandler(btnIndividualLogout_Click);
            divConnections.Controls.Add(logoutBtn);
        }

        if (SocialAuthUser.IsLoggedIn())
        {
            IsSTSaware     = HttpContext.Current.ApplicationInstance.IsSTSaware();
            Provider       = User.Identity.GetProvider();
            Pid            = User.Identity.GetProfile().ID;
            Identifier     = User.Identity.GetProfile().GetIdentifier();
            Username       = User.Identity.GetProfile().Username;
            Displayname    = User.Identity.GetProfile().DisplayName;
            Email          = User.Identity.GetProfile().Email;
            Fullname       = User.Identity.GetProfile().FullName;
            FirstName      = User.Identity.GetProfile().FirstName;
            LastName       = User.Identity.GetProfile().LastName;
            DateOfBirth    = User.Identity.GetProfile().DateOfBirth;
            Gender         = User.Identity.GetProfile().Gender.ToString();
            ProfileURL     = User.Identity.GetProfile().ProfileURL;
            ProfilePicture = User.Identity.GetProfile().ProfilePictureURL;
            Country        = User.Identity.GetProfile().Country;
            Language       = User.Identity.GetProfile().Language;
            AccessToken    = SocialAuthUser.GetCurrentUser().GetAccessToken();
            bool IsAlternate = false;

            try
            {
                User.Identity.GetContacts().ForEach(
                    x =>
                {
                    HtmlTableRow tr = new HtmlTableRow();
                    tr.Attributes.Add("class", (IsAlternate) ? "dark" : "light");
                    tr.Cells.Add(new HtmlTableCell()
                    {
                        InnerText = x.Name
                    });
                    tr.Cells.Add(new HtmlTableCell()
                    {
                        InnerText = x.Email
                    });
                    tr.Cells.Add(new HtmlTableCell()
                    {
                        InnerText = x.ProfileURL
                    });
                    tblContacts.Rows.Add(tr);
                    IsAlternate = !IsAlternate;
                }

                    );
                ContactsCount = (tblContacts.Rows.Count - 1).ToString();
            }
            catch (Exception ex)
            {
                contacts.InnerHtml = "<error>" + ex.Message + "</error>";
            }
        }
        else
        {
            Response.Write("You are not logged in..");
        }
    }
        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();
                        }
                    }
                }
            }
        }