Ejemplo n.º 1
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());
        }
        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());
                    }
                }
            }
        }