Ejemplo n.º 1
0
        public static bool ValidateWithSlidingWindow(RPSTicket rpsTicket, TimeSpan slidingWindow)
        {
            RPSPropBag rpspropBag = null;

            try
            {
                rpspropBag = new RPSPropBag(LiveIdAuthentication.rpsOrgIdSession);
                rpspropBag["SlidingWindow"] = slidingWindow.TotalSeconds;
                if (!rpsTicket.Validate(rpspropBag))
                {
                    int num = (int)rpspropBag["ReasonHR"];
                    if (num == -2147184087)
                    {
                        return(false);
                    }
                }
            }
            catch (COMException e)
            {
                LiveIdErrorHandler.ThrowRPSException(e);
            }
            finally
            {
                if (rpspropBag != null)
                {
                    rpspropBag.Dispose();
                }
            }
            return(true);
        }
Ejemplo n.º 2
0
        public string GetLiveIDUrl(RouteCollection routes, RequestContext context, string urlType)
        {
            RPS globalRPS = GetRPS(context);

            if (globalRPS == null)
            {
                return("");
            }

            RPSPropBag loginUrlProperties = new RPSPropBag(globalRPS);

            loginUrlProperties["ReturnURL"] = new UrlHelper(context, routes).AbsolutePath(context.HttpContext.Request.Url.AbsolutePath);

            string siteName = GetSiteName();

            try
            {
                return(new RPSDomainMap(globalRPS).ConstructURL(urlType, siteName, null, loginUrlProperties));
            }
            catch
            {
                return("");
            }
        }
Ejemplo n.º 3
0
        public IUser GetUser(RequestContext context)
        {
            HttpRequest request = (HttpRequest)context.HttpContext.Items["originalRequest"];

            if (context.HttpContext.Items.Contains("CalledLiveIDAlready"))
            {
                if (context.HttpContext.Items.Contains(typeof(IUser).FullName))
                {
                    return(context.HttpContext.Items[typeof(IUser).FullName] as IUser);
                }
            }


            context.HttpContext.Items.Add("CalledLiveIDAlready", "Did it");

            HttpResponse response    = (HttpResponse)context.HttpContext.Items["originalResponse"];
            IUserService userService = container.Resolve <IUserService>();

            // Get the RPS object preinitialized in the Global.asax
            RPS myRps = GetRPS(context);

            if (myRps == null)
            {
                return(null);
            }
            string siteName = GetSiteName();

            // Create other base RPS objects.
            RPSHttpAuth  httpAuth    = new RPSHttpAuth(myRps);
            RPSPropBag   authPropBag = new RPSPropBag(myRps);
            RPSDomainMap domainMap   = new RPSDomainMap(myRps);

            RPSServerConfig mainConfig = new RPSServerConfig(myRps);
            RPSPropBag      siteConfig = (RPSPropBag)mainConfig["Sites"];

            RPSPropBag mySiteConfig = (RPSPropBag)siteConfig[siteName];

            int siteID = Convert.ToInt32(mySiteConfig["SiteID"]);

            // Set returnUrl and siteID in authPropBag.

            // Determine if SSL should be used.
            string returnUrl;

            if (context.HttpContext.Request.IsSecureConnection)
            {
                returnUrl = "https://"
                            + context.HttpContext.Request.ServerVariables["SERVER_NAME"]
                            + context.HttpContext.Request.Path;
            }
            else
            {
                returnUrl = "http://"
                            + context.HttpContext.Request.ServerVariables["SERVER_NAME"]
                            + context.HttpContext.Request.Path;
            }

            authPropBag["ReturnURL"] = returnUrl;
            authPropBag["SiteID"]    = siteID;

            // Create ticket object and populate the authPropBag with
            // values from the Request object.
            RPSTicket ticket = httpAuth.Authenticate(siteName, request, authPropBag);

            // Get the user's 'authState' to determine if user is currently signed in.
            uint authState = (uint)authPropBag["RPSAuthState"];

            if (ticket == null)
            {
                //No RPSTicket found.  Check for AuthState=2 (Maybe) state.
                if (authState == 2)
                {
                    // RPS Maybe state detected. Indicates a ticket is present,
                    // but cannot be read. Redirect to SilentAuth URL to obtain
                    // a fresh RPS Ticket. Write RPS response headers to write
                    // the Maybe state cookie to prevent looping.
                    string rpsHeaders = (string)authPropBag["RPSRespHeaders"];
                    if (rpsHeaders != "")
                    {
                        httpAuth.WriteHeaders(response, rpsHeaders);
                    }

                    string silentAuthUrl =
                        domainMap.ConstructURL(
                            "SilentAuth",
                            siteName,
                            null,
                            authPropBag);
                    context.HttpContext.Response.Redirect(silentAuthUrl);
                }
                else
                {
                    // User is not signed in.  Show page with Sign-in option.

                    //Message.Text = "A ticket was not detected. "
                    //    + "Click the sign in button below to sign in.";
                    //ShowTicketProperties.Text = "";
                    //bool showSignIn = true;
                    //bool isSecure = Request.IsSecureConnection;

                    //LogoButton.Text =
                    //    httpAuth.LogoTag(
                    //        showSignIn,
                    //        isSecure,
                    //        null,
                    //        null,
                    //        siteName,
                    //        authPropBag);
                }
            }
            else
            {
                // RPS ticket found. Ensure ticket is valid (signature is valid
                // and policy criteria such as time window and use of SSL are met).

                bool isValid = ticket.Validate(authPropBag);

                if (!isValid)
                {
                    // RPS ticket exists, but is not valid. Refresh ticket by
                    // redirecting user to Auth URL. If appropriate Login server
                    // cookies exist, ticket refresh will be transparent to the user.
                    context.HttpContext.Response.Redirect(
                        domainMap.ConstructURL(
                            "Auth",
                            siteName,
                            null,
                            authPropBag));
                }
                else
                {
                    //Get RPS response headers from authPropBag and write to response stream
                    string rpsHeaders = (string)authPropBag["RPSRespHeaders"];
                    if (rpsHeaders != "")
                    {
                        httpAuth.WriteHeaders(response, rpsHeaders);
                    }

                    UserAuthenticated user = userService.GetUserByModuleData("LiveID", (string)ticket.Property["HexPUID"]);

                    if (user == null)
                    {
                        UrlHelper urlHelper = new UrlHelper(context);

                        if (!urlHelper.IsRegisterRoute() && !urlHelper.IsSignOutRoute() && !urlHelper.IsErrorRoute())
                        {
                            context.HttpContext.Response.Redirect(urlHelper.Register(), true);
                        }

                        IDictionary <string, object> values = new Dictionary <string, object>();

                        values.Add("PUID", (string)ticket.Property["HexPUID"]);
                        values.Add("FirstName", (string)ticket.ProfileProperty["firstname"]);
                        values.Add("LastName", (string)ticket.ProfileProperty["lastname"]);

                        return(new UserUnregistered("Unregistered User", "LiveID", values));
                    }
                    else
                    {
                        user.AuthenticationValues["PUID"]      = (string)ticket.Property["HexPUID"];
                        user.AuthenticationValues["FirstName"] = (string)ticket.ProfileProperty["firstname"];
                        user.AuthenticationValues["LastName"]  = (string)ticket.ProfileProperty["lastname"];
                    }

                    return(user);
                }
            }


            return(new UserAnonymous());
        }
Ejemplo n.º 4
0
        public static bool Authenticate(HttpContext httpContext, string siteName, string authPolicyOverrideValue, string[] memberNameIgnorePrefixes, bool useConsumerRps, out string puid, out string orgIdPuid, out string cid, out string membername, out uint issueTime, out uint loginAttributes, out string responseHeaders, out uint rpsTicketType, out RPSTicket deprecatedRpsTicketObject, out bool hasAcceptedAccrual, out uint rpsAuthState, out bool isOrgIdFederatedMsaIdentity)
        {
            if (!LiveIdAuthentication.IsInitialized)
            {
                throw new InvalidOperationException(Strings.ComponentNotInitialized);
            }
            if (siteName == null)
            {
                throw new ArgumentNullException("siteName");
            }
            hasAcceptedAccrual = false;
            puid                        = null;
            orgIdPuid                   = null;
            cid                         = null;
            membername                  = null;
            issueTime                   = 0U;
            loginAttributes             = 0U;
            responseHeaders             = null;
            rpsTicketType               = 0U;
            deprecatedRpsTicketObject   = null;
            rpsAuthState                = 0U;
            isOrgIdFederatedMsaIdentity = false;
            RPSPropBag rpspropBag = null;
            string     text       = httpContext.Request.QueryString["f"];

            if (!string.IsNullOrEmpty(text))
            {
                ExTraceGlobals.LiveIdAuthenticationModuleTracer.TraceError <string>(0L, "Querystring contains F-code: {0}.", text);
                return(false);
            }
            try
            {
                if (!useConsumerRps)
                {
                    rpspropBag = new RPSPropBag(LiveIdAuthentication.rpsOrgIdSession);
                }
                RPSProfile rpsprofile = null;
                using (RPSHttpAuthClient rpshttpAuthClient = LiveIdAuthentication.CreateRPSClient(useConsumerRps))
                {
                    int?   rpsErrorCode;
                    string rpsErrorString;
                    rpsprofile = rpshttpAuthClient.Authenticate(siteName, authPolicyOverrideValue, LiveIdAuthentication.sslOffloaded, httpContext.Request, rpspropBag, out rpsErrorCode, out rpsErrorString, out deprecatedRpsTicketObject);
                    LiveIdAuthentication.ValidateRpsCallAndThrowOnFailure(rpsErrorCode, rpsErrorString);
                }
                if (rpsprofile == null)
                {
                    return(false);
                }
                if (!useConsumerRps && deprecatedRpsTicketObject != null)
                {
                    try
                    {
                        using (RPSPropBag rpspropBag2 = new RPSPropBag(LiveIdAuthentication.rpsOrgIdSession))
                        {
                            rpspropBag2["SlidingWindow"] = 0;
                            if (!string.IsNullOrEmpty(authPolicyOverrideValue))
                            {
                                rpspropBag2["AuthPolicy"] = authPolicyOverrideValue;
                            }
                            if (!deprecatedRpsTicketObject.Validate(rpspropBag2))
                            {
                                return(false);
                            }
                        }
                    }
                    catch (COMException ex)
                    {
                        ExTraceGlobals.LiveIdAuthenticationModuleTracer.TraceError <COMException>(0L, "Failed to validate ticket: {0}.", ex);
                        LiveIdErrorHandler.ThrowRPSException(ex);
                    }
                }
                rpsAuthState  = rpsprofile.RPSAuthState;
                rpsTicketType = rpsprofile.TicketType;
                if (LiveIdAuthenticationModule.AppPasswordCheckEnabled && !httpContext.Request.Url.AbsolutePath.StartsWith("/owa/", StringComparison.OrdinalIgnoreCase) && rpsprofile.AppPassword)
                {
                    AppPasswordAccessException exception = new AppPasswordAccessException();
                    httpContext.Response.AppendToLog("&AppPasswordBlocked");
                    Utilities.HandleException(httpContext, exception, false);
                }
                hasAcceptedAccrual = LiveIdAuthentication.HasAcceptedAccruals(rpsprofile);
                orgIdPuid          = rpsprofile.HexPuid;
                cid        = (string.IsNullOrWhiteSpace(rpsprofile.ConsumerCID) ? rpsprofile.HexCID : rpsprofile.ConsumerCID);
                puid       = (string.IsNullOrWhiteSpace(rpsprofile.ConsumerPuid) ? orgIdPuid : rpsprofile.ConsumerPuid);
                membername = rpsprofile.MemberName;
                string text2;
                if (LiveIdAuthentication.TryRemoveMemberNamePrefixes(membername, memberNameIgnorePrefixes, out text2))
                {
                    membername = text2;
                    isOrgIdFederatedMsaIdentity = true;
                }
                issueTime       = rpsprofile.IssueInstant;
                loginAttributes = rpsprofile.LoginAttributes;
                string text3 = loginAttributes.ToString();
                httpContext.Response.AppendToLog("&loginAttributes=" + text3);
                if (!string.IsNullOrWhiteSpace(text3))
                {
                    httpContext.Response.AppendToLog(string.Format("loginAttributes={0}", text3));
                    httpContext.Request.Headers.Add("X-LoginAttributes", text3);
                }
                responseHeaders = rpsprofile.ResponseHeader;
            }
            finally
            {
                if (rpspropBag != null)
                {
                    rpspropBag.Dispose();
                }
            }
            return(true);
        }
        private void HandleMicrosoftPassportAuthentication(AuthenticationContext filterContext)
        {
            HttpContextBase context = filterContext.HttpContext;

            Microsoft.Passport.RPS.RPS myRps = (Microsoft.Passport.RPS.RPS)context.Application["globalRPS"];
            string siteName = ConfigurationManager.AppSettings["SiteName"];

            Microsoft.Passport.RPS.RPSHttpAuth httpAuth = new Microsoft.Passport.RPS.RPSHttpAuth(myRps);
            RPSPropBag      authPropBag      = new RPSPropBag(myRps);
            RPSDomainMap    domainMap        = new RPSDomainMap(myRps);
            RPSServerConfig mainConfig       = new RPSServerConfig(myRps);
            RPSPropBag      siteConfig       = (RPSPropBag)mainConfig["Sites"];
            RPSPropBag      mySiteConfig     = (RPSPropBag)siteConfig[siteName];
            int             siteID           = Convert.ToInt32(mySiteConfig["SiteID"]);
            var             returnUrlBuilder = new UriBuilder(context.Request.Url);

            returnUrlBuilder.Scheme  = Uri.UriSchemeHttps;
            returnUrlBuilder.Port    = 443;
            authPropBag["ReturnURL"] = returnUrlBuilder.ToString();
            authPropBag["SiteID"]    = siteID;
            RPSTicket ticket = null;

            try
            {
                ticket = httpAuth.Authenticate(siteName, HttpContext.Current.Request, authPropBag);
            }
            catch (Exception e)
            {
                ticket = null;
            }

            // Get the user's 'authState' to determine whether user is currently signed in.
            uint authState = (uint)authPropBag["RPSAuthState"];

            if (ticket == null)
            {
                //No RPSTicket found.  Check for AuthState=2 (Maybe) state.
                if (authState == 2)
                {
                    // RPS Maybe state detected. Indicates that a ticket is present
                    // but cannot be read. Redirect to SilentAuth URL to obtain
                    // a fresh RPS Ticket. Write RPS response headers to write
                    // the Maybe state cookie to prevent looping.
                    string rpsHeaders = (string)authPropBag["RPSRespHeaders"];
                    if (rpsHeaders != "")
                    {
                        httpAuth.WriteHeaders(HttpContext.Current.Response, rpsHeaders);
                    }

                    string silentAuthUrl = domainMap.ConstructURL("SilentAuth", siteName, null, authPropBag);
                    HttpContext.Current.Response.Redirect(silentAuthUrl);
                }
                else
                {
                    bool             showSignIn = true;
                    bool             isSecure   = HttpContext.Current.Request.IsSecureConnection;
                    string           signInHtml = httpAuth.LogoTag(showSignIn, isSecure, null, null, siteName, authPropBag);
                    LiveIdAuthResult result     = new LiveIdAuthResult();
                    result.IsUserAuthenticated     = false;
                    result.SignInHtmlLink          = signInHtml;
                    context.Items["liveauthstate"] = result;
                }
            }
            else
            {
                // RPS ticket found. Ensure ticket is valid (signature is valid
                // and policy criteria such as time window and use of SSL are met).
                bool isValid = ticket.Validate(authPropBag);
                if (!isValid)
                {
                    // RPS ticket exists, but is not valid. Refresh ticket by
                    // redirecting user to "Auth" URL. If appropriate Login Server
                    // cookies exist, ticket refresh will be transparent to the user.
                    HttpContext.Current.Response.Redirect(domainMap.ConstructURL("Auth", siteName, null, authPropBag));
                }
                else
                {
                    //// RPS ticket exists and is valid. Show page with sign-out
                    //// button and user's NetID.


                    bool   showSignIn  = false;
                    bool   isSecure    = HttpContext.Current.Request.IsSecureConnection;
                    string signOutHtml = httpAuth.LogoTag(showSignIn, isSecure, null, null, siteName, authPropBag);

                    LiveIdAuthResult result = new LiveIdAuthResult();
                    result.IsUserAuthenticated = true;
                    result.SignOutHtmlLink     = signOutHtml;

                    string        puid         = (string)ticket.Property["HexPUID"];
                    uint          ticketType   = ticket.TicketType;
                    string        clearTicket  = (string)ticket.Property["ClearTicket"];
                    System.UInt32 issueInstant = (System.UInt32)ticket.Property["IssueInstant"];

                    if (ticket != null & ticket.ProfileProperty["memberName"] != null)
                    {
                        string   profileName  = (string)ticket.ProfileProperty["memberName"];
                        string   firstName    = (string)ticket.ProfileProperty["firstname"];
                        string   lastName     = (string)ticket.ProfileProperty["lastname"];
                        string   gender       = (string)ticket.ProfileProperty["gender"];
                        DateTime?birthdate    = (DateTime?)ticket.ProfileProperty["birthdate"];
                        string   city         = (string)ticket.ProfileProperty["city"];
                        int      region       = (int)ticket.ProfileProperty["region"];
                        string   country      = (string)ticket.ProfileProperty["country"];
                        string   postalcode   = (string)ticket.ProfileProperty["postalcode"];
                        string   revipcountry = (string)ticket.ProfileProperty["revipcountry"];

                        Int32 myflags = myflags = (Int32)ticket.ProfileProperty["flags"];
                        bool  f2bit   = (myflags & 0x2) == 0x2;               //Hotmail enabled
                        bool  f4bit   = (myflags & 0x4) == 0x4;               // Mobile Subscriber
                        bool  f5bit   = (myflags & 0x10) == 0x10;             // User is blocked
                        bool  f10bit  = (myflags & 0x200) == 0x200;           //Mobile Subscriber
                        bool  f11bit  = (myflags & 0x400) == 0x400;           //E-mail Address Verified
                        bool  f12bit  = (myflags & 0x800) == 0x800;           //Primary MSNIA subscription
                        bool  f13bit  = (myflags & 0x1000) == 0x1000;         //Mobile subscription
                        bool  f14bit  = (myflags & 0x2000) == 0x2000;         //Hotmail Premium subscription
                        bool  f16bit  = (myflags & 0x8000) == 0x8000;         //Managed domain
                        bool  f17bit  = (myflags & 0x10000) == 0x10000;       //MSN subscription-no age-out
                        bool  f18bit  = (myflags & 0x20000) == 0x20000;       //Secondary MSNIA subscription
                        bool  f19bit  = (myflags & 0x40000) == 0x40000;       //Verizon user
                        bool  f20bit  = (myflags & 0x80000) == 0x80000;       //MSN Direct subscription
                        bool  f21bit  = (myflags & 0x100000) == 0x100000;     //User does not age out
                        bool  f22bit  = (myflags & 0x200000) == 0x200000;     //HIP challenge not required
                        bool  f30bit  = (myflags & 0x20000000) == 0x20000000; //WLTOU Not accepted

                        // Get RPS response headers from authPropBag and write to response stream
                        string rpsHeaders = (string)authPropBag["RPSRespHeaders"];
                        if (rpsHeaders != "")
                        {
                            httpAuth.WriteHeaders(HttpContext.Current.Response, rpsHeaders);
                            result.RpsHeaders = rpsHeaders;
                        }

                        result.ProfileName = firstName + " " + lastName;
                    }

                    result.Anid = TokenHelper.ConvertPuidToAnid(puid);
                    context.Items["liveauthstate"] = result;
                    filterContext.Principal        = TokenHelper.GetClaimsPrincipal(result.Anid, result.ProfileName, "custompassportauth", puid);

                    string data = WriteAuthDataToAuthCookie(puid, result.ProfileName, null);
                    context.Items["backendtoken"] = data;

                    // Convert Post to Get
                    var query = new NameValueCollection(context.Request.QueryString);
                    var wa    = query["wa"];
                    if (string.Compare(wa, "wsignin1.0", true) == 0)
                    {
                        query.Remove("wa");
                        UriBuilder builder = new UriBuilder(context.Request.Url);
                        builder.Query = ConvertToQueryString(query);
                        filterContext.HttpContext.Response.Redirect(builder.ToString());
                    }
                }
            }
        }