Пример #1
0
 public async Task<Result> DeleteData(Uri uri, StringContent json, UserAccountEntity userAccountEntity)
 {
     var httpClient = new HttpClient();
     try
     {
         var authenticationManager = new AuthenticationManager();
         if (userAccountEntity.GetAccessToken().Equals("refresh"))
         {
             await authenticationManager.RefreshAccessToken(userAccountEntity);
         }
         var user = userAccountEntity.GetUserEntity();
         if (user != null)
         {
             var language = userAccountEntity.GetUserEntity().Language;
             httpClient.DefaultRequestHeaders.Add("Accept-Language", language);
         }
         httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
         var response = await httpClient.DeleteAsync(uri);
         var responseContent = await response.Content.ReadAsStringAsync();
         return response.IsSuccessStatusCode ? new Result(true, string.Empty) : new Result(false, responseContent);
     }
     catch (Exception)
     {
         return new Result(false, string.Empty);
     }
 }
        public void AzureADAuthFullControlPermissionTest()
        {
            string siteUrl = TestCommon.DevSiteUrl;
            string spoUserName = AuthenticationTests.UserName;
            string azureADCertPfxPassword = TestCommon.AzureADCertPfxPassword;
            string azureADClientId = TestCommon.AzureADClientId;

            if (String.IsNullOrEmpty(azureADCertPfxPassword) ||
                String.IsNullOrEmpty(azureADClientId) ||
                String.IsNullOrEmpty(spoUserName) ||
                String.IsNullOrEmpty(siteUrl))
            {
                Assert.Inconclusive("Not enough information to execute this test is passed via the app.config file.");
            }

            ClientContext cc = null;

            try
            {
                string domain = spoUserName.Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries)[1];

                // Instantiate a ClientContext object based on the defined Azure AD application
                if (new Uri(siteUrl).DnsSafeHost.Contains("spoppe.com"))
                {
                    cc = new AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(siteUrl, azureADClientId, domain, @"resources\PnPAzureAppTest.pfx", azureADCertPfxPassword, AzureEnvironment.PPE);
                }
                else
                {
                    cc = new AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(siteUrl, azureADClientId, domain, @"resources\PnPAzureAppTest.pfx", azureADCertPfxPassword);
                }

                // Check if we can read a property from the site
                cc.Load(cc.Web, w => w.Title);
                cc.ExecuteQueryRetry();
                Console.WriteLine(String.Format("Site title: {0}", cc.Web.Title));

                // Verify manage permissions by creating a new list - see https://technet.microsoft.com/en-us/library/cc721640.aspx
                var list = cc.Web.CreateList(ListTemplateType.DocumentLibrary, "Test_list_" + DateTime.Now.ToFileTime(), false);

                // Verify full control by enumerating permissions - see https://technet.microsoft.com/en-us/library/cc721640.aspx
                var roleAssignments = cc.Web.GetAllUniqueRoleAssignments();

                // Nothing blew up...so we're good :-)

            }
            finally
            {
                cc.Dispose();
            }
        }
        public async Task Providing_Invalid_Credentials_Returns_False()
        {
            var cookieContainer = new CookieContainer();
            cookieContainer.Add(new Uri("http://foo.com"), new Cookie("Bar", "Foo"));
            var webManager = new FakeWebManager
            {
                CookiesToReturn = cookieContainer
            };

            var localStorage = new FakeLocalStorageManager();
            var am = new AuthenticationManager(webManager, localStorage);
            const bool expected = false;
            bool actual = await am.Authenticate("foo", "bar");
            Assert.AreEqual(expected, actual);
        }
        public async Task Network_Interface_Being_Unavailable_Throws_Exception()
        {
            var cookieContainer = new CookieContainer();
            cookieContainer.Add(new Uri("http://foo.com"), new Cookie("Bar", "Foo"));
            var webManager = new FakeWebManager
            {
                CookiesToReturn = cookieContainer,
                IsNetworkAvailable = false
            };

            var localStorage = new FakeLocalStorageManager();
            var am = new AuthenticationManager(webManager, localStorage);
            try
            {
                await am.Authenticate("foo", "bar");
            }
            catch (Exception)
            {
                return;
            }
            Assert.Fail();
        }
Пример #5
0
        public async Task<Result> PostData(Uri uri, MultipartContent header, StringContent content, UserAccountEntity userAccountEntity)
        {
            var httpClient = new HttpClient();
            try
            {
                var authenticationManager = new AuthenticationManager();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                var user = userAccountEntity.GetUserEntity();
                if (user != null)
                {
                    var language = userAccountEntity.GetUserEntity().Language;
                    httpClient.DefaultRequestHeaders.Add("Accept-Language", language);
                }

                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                HttpResponseMessage response;
                if (header == null)
                {
                    response = await httpClient.PostAsync(uri, content);
                }
                else
                {
                    response = await httpClient.PostAsync(uri, header);
                }
                var responseContent = await response.Content.ReadAsStringAsync();
                return new Result(true, responseContent);
            }
            catch
            {
                // TODO: Add detail error result to json object.
                return new Result(false, string.Empty);
            }
        }
 public static void Authenticate_NotSupported()
 {
     Assert.Throws <PlatformNotSupportedException>(() => AuthenticationManager.Authenticate(null, null, null));
     Assert.Throws <PlatformNotSupportedException>(() => AuthenticationManager.PreAuthenticate(null, null));
 }
Пример #7
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }
            if (loginInfo.Login.LoginProvider == "Facebook")
            {
                var     identity     = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
                var     access_token = identity.FindFirstValue("FacebookAccessToken");
                var     fb           = new FacebookClient(access_token);
                dynamic myInfo       = fb.Get("/me?fields=email");
                loginInfo.Email = myInfo.email;
            }
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                var user = new ApplicationUser {
                    UserName = loginInfo.DefaultUserName, Email = loginInfo.Email
                };
                if (UserManager.FindByEmail(user.Email) == null)
                {
                    var resultt = await UserManager.CreateAsync(user);

                    if (resultt.Succeeded)
                    {
                        resultt = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);

                        if (resultt.Succeeded)
                        {
                            await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                            return(RedirectToLocal(returnUrl));
                        }
                    }
                }
                else
                {
                    var resultt = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);

                    if (resultt.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        return(RedirectToLocal(returnUrl));
                    }
                }
                return(RedirectToLocal(returnUrl));
            }
            //else
            //{
            //    ViewBag.ReturnUrl = returnUrl;
            //    ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
            //    var newUser = new ApplicationUser { UserName = loginInfo.Email, Email = loginInfo.Email };
            //    var newResult = await UserManager.CreateAsync(newUser, "Nhy6&*()");
            //    await SignInManager.PasswordSignInAsync(loginInfo.Email, "Nhy6&*()",
            //        false, shouldLockout: false);
            //    return RedirectToAction("List", "Event");
            //}
            //switch (result)
            //{
            //    case SignInStatus.Success:
            //        return RedirectToLocal(returnUrl);
            //    case SignInStatus.LockedOut:
            //        return View("Lockout");
            //    case SignInStatus.RequiresVerification:
            //        return RedirectToAction("SendCode", new {ReturnUrl = returnUrl, RememberMe = false});
            //    case SignInStatus.Failure:
            //    default:
            //        // If the user does not have an account, then prompt the user to create an account
            //        ViewBag.ReturnUrl = returnUrl;
            //        ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
            //        var newUser = new ApplicationUser { UserName = loginInfo.Email, Email = loginInfo.Email };
            //        var newResult = await UserManager.CreateAsync(newUser, "Nhy6&*()");
            //        await SignInManager.PasswordSignInAsync(loginInfo.Email, "Nhy6&*()",
            //            false, shouldLockout: false);
            //        return RedirectToLocal(returnUrl);
            //        //return View("ExternalLoginConfirmation",
            //        //    new ExternalLoginConfirmationViewModel { UserName = loginInfo.ExternalIdentity.Name ,Email = loginInfo.Email });
            //}
        }
 /// <summary>
 /// 注销
 /// </summary>
 public void SignOut()
 {
     AuthenticationManager.SignOut();
     HttpContext.Current.Session.RemoveAll();
     // return HttpContext.Current.Request.r("Index", "Home");
 }
Пример #9
0
        /// <summary>
        /// Проверка и регистрация пользователя
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="isPersistent"></param>
        /// <param name="shouldLockout"></param>
        /// <returns></returns>

        public virtual async Task <SignInCode> PasswordSignInAsync(string userName, string password, bool isPersistent,
                                                                   bool shouldLockout)
        {
#if DEBUG
            Debug.WriteLine("**** Begin PasswordSignInAsync *****");
#endif
            if (UserManager == null)
            {
                return(SignInCode.Failure);
            }

            var user = await _myUserManager.FindByNameAsync(userName); //.WithCurrentCulture();

            if (user == null)
            {
                return(SignInCode.Failure);
            }
#if DEBUG
            else
            {
                Debug.WriteLine("user is not null");
            }
#endif
            // должны ли учётки блокироваться
            // await _myUserManager.SetLockoutEnabledAsync(user.UserID, shouldLockout);



            //Проверка пароля
            if (await _myUserManager.CheckPasswordAsync(user, password)) //.WithCurrentCulture())
            {
#if DEBUG
                Debug.WriteLine("* CheckPasswordAsync *");
                Debug.WriteLine("SignInCode.Success!!");
#endif



                // Проверка на постоянную блокировку
                if (await _myUserManager.GetLockoutEnabledAsync(user.UserID))
                {
                    return(SignInCode.LockedOut);
                }

                // Активизирована ли функция  блокировки учётки в системе
                if (_myUserManager.LockoutEnabled)
                {
                    // Блокирована ли учётка?
                    if (await _myUserManager.IsLockedOutAsync(user.UserID)) //.WithCurrentCulture())
                    {
#if DEBUG
                        Debug.WriteLine("user is lockedout");
#endif
                        return(SignInCode.LockedOut);
                    }
#if DEBUG
                    else
                    {
                        Debug.WriteLine("user is not lockedout");
                    }
#endif

                    // Проверка как давно не было входа в систему
                    if (!await _myUserManager.CheckLastSigninAsync(user))
                    {
                        // Вход в систему был больше положенного срока
                        await _myUserManager.SetLockoutEnabledAsync(user.UserID, true);

                        return(SignInCode.LockedOut);
                    }
                }



                // Пароль верный

                // Проверка даты последнего изменения пароля
                if (await _myUserManager.CheckLastSetPasswordAsync(user))
                {
#if DEBUG
                    Debug.WriteLine("+++ CheckLastSetPasswordAsync is true");
#endif
                    // Регистрация в системе
                    AuthenticationManager.SignOut();
                    var identity = await _myUserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

                    AuthenticationManager.SignIn(identity);
                    if (_myUserManager.LockoutEnabled)
                    {
                        await _myUserManager.ResetAccessFailedCountAsync(user.UserID);

                        await _myUserManager.SetSigninEndDateAsync(user);
                    }
                    return(SignInCode.Success);
                }
                else
                {
                    // Настал период изменения пароля
#if DEBUG
                    Debug.WriteLine("+++ CheckLastSetPasswordAsync is false");
#endif
                    return(SignInCode.ChangePassword);
                }


                //return await SignInOrTwoFactor(user, isPersistent).WithCurrentCulture();
            }

            else
            {
                // Пароль неверный
#if DEBUG
                Debug.WriteLine("* CheckPasswordAsync *");
                Debug.WriteLine("SignInCode.Failure!");
#endif

                // Активизирована ли функция  блокировки учётки в системе
                if (_myUserManager.LockoutEnabled)
                {
#if DEBUG
                    Debug.WriteLine("++++ GetLockoutEnabledAsync is enabled");
#endif
                    // Увелечение счётчика неудачных попыток ввода пароля
                    if (await _myUserManager.AccessFailedAsync(user.UserID) == IdentityResult.Success)
                    {
#if DEBUG
                        Debug.WriteLine("~~~ AccessFailedAsync is working!");
#endif
                        if (await _myUserManager.IsLockedOutAsync(user.UserID))
                        {
                            //Заблокировать учётку
                            return(SignInCode.LockedOut);
                        }
                    }
                }
#if DEBUG
                else
                {
                    Debug.WriteLine("++++ GetLockoutEnabledAsync is disabled");
                }
#endif
            }


            return(SignInCode.Failure);
        }
Пример #10
0
 public async Task<ActionResult> LogOff()
 {
     await SignOutAsync();
     AuthenticationManager.SignOut();
     return RedirectToAction("Index", "Home");
 }
Пример #11
0
 public ActionResult LogOff()
 {
     AuthenticationManager.SignOut();
     return(RedirectToAction("Login", "Account"));
 }
Пример #12
0
 /// <summary>
 /// 注销
 /// </summary>
 public void LoginOut()
 {
     AuthenticationManager.SignOut();
 }
Пример #13
0
 public async Task<Result> GetData(Uri uri, UserAccountEntity userAccountEntity)
 {
     var httpClient = new HttpClient();
     try
     {
         var authenticationManager = new AuthenticationManager();
         if (userAccountEntity.GetAccessToken().Equals("refresh"))
         {
             await authenticationManager.RefreshAccessToken(userAccountEntity);
         }
         var user = userAccountEntity.GetUserEntity();
         if (user != null)
         {
             var language = userAccountEntity.GetUserEntity().Language;
             httpClient.DefaultRequestHeaders.Add("Accept-Language", language);
         }
         httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
         var response = await httpClient.GetAsync(uri);
         if (response.StatusCode == HttpStatusCode.NotFound)
         {
             throw new WebException("PSN API Error: Service not found.");
         }
         var responseContent = await response.Content.ReadAsStringAsync();
         return string.IsNullOrEmpty(responseContent) ? new Result(false, string.Empty) : new Result(true, responseContent);
     }
     catch
     {
         throw new WebException("PSN API Error: Service not found.");
     }
 }
Пример #14
0
		private void AttachToVisualTree()
		{
			_webBrowser = GetTemplateChild(AuthBrowserName) as WebControl;
			if (_webBrowser == null)
				throw new InvalidOperationException("WebControl not found!");

			_webBrowser.BeginNavigation += WebBrowserOnBeginNavigation;

			_authenticationManager = new AuthenticationManager(Properties.Resources.EngageHtml);
			_authenticationManager.TokenReceived += AuthenticationManagerOnTokenReceived;
			_authenticationManager.BusyStateChanged += AuthenticationManagerOnBusyStateChanged;
			_authenticationManager.Initialize(this);

			SwitchAccounts = new SwitchAccountsCommand(_authenticationManager);
		}
        public void BasicPublishingPageOnPremisesTest()
        {
            using (var targetClientContext = TestCommon.CreateClientContext("https://bertonline.sharepoint.com/sites/modernizationusermapping"))
            {
                //https://bertonline.sharepoint.com/sites/modernizationtestportal
                //using (var sourceClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPODevSiteUrl")))
                AuthenticationManager authManager = new AuthenticationManager();
                using (var sourceClientContext = authManager.GetOnPremisesContext("https://portal2013.pnp.com/sites/devportal"))
                {
                    //"C:\github\sp-dev-modernization\Tools\SharePoint.Modernization\SharePointPnP.Modernization.Framework.Tests\Transform\Publishing\custompagelayoutmapping.xml"
                    //"C:\temp\mappingtest.xml"
                    var pageTransformator = new PublishingPageTransformator(sourceClientContext, targetClientContext, @"c:\github\zzscratch\pagelayoutmapping.xml");
                    pageTransformator.RegisterObserver(new MarkdownObserver(folder: "c:\\temp", includeVerbose: true));


                    var pages = sourceClientContext.Web.GetPagesFromList("Pages", "bug268");
                    //var pages = sourceClientContext.Web.GetPagesFromList("Pages", folder:"News");

                    foreach (var page in pages)
                    {
                        PublishingPageTransformationInformation pti = new PublishingPageTransformationInformation(page)
                        {
                            // If target page exists, then overwrite it
                            Overwrite = true,

                            // Don't log test runs
                            SkipTelemetry = true,

                            KeepPageCreationModificationInformation = true,

                            PostAsNews      = true,
                            UserMappingFile = @"C:\github\pnpframework\src\lib\PnP.Framework.Modernization.Test\Transform\Mapping\usermapping_sample2.csv",

                            //RemoveEmptySectionsAndColumns = false,

                            // Configure the page header, empty value means ClientSidePageHeaderType.None
                            //PageHeader = new ClientSidePageHeader(cc, ClientSidePageHeaderType.None, null),

                            // Replace embedded images and iframes with a placeholder and add respective images and video web parts at the bottom of the page
                            // HandleWikiImagesAndVideos = false,

                            // Callout to your custom code to allow for title overriding
                            //PageTitleOverride = titleOverride,

                            // Callout to your custom layout handler
                            //LayoutTransformatorOverride = layoutOverride,

                            // Callout to your custom content transformator...in case you fully want replace the model
                            //ContentTransformatorOverride = contentOverride,
                        };

                        pti.MappingProperties["SummaryLinksToQuickLinks"] = "true";
                        pti.MappingProperties["UseCommunityScriptEditor"] = "true";

                        var result = pageTransformator.Transform(pti);
                    }

                    pageTransformator.FlushObservers();
                }
            }
        }
Пример #16
0
 public ActionResult ForgetBrowser()
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
     return(RedirectToAction("Index", "Manage"));
 }
Пример #17
0
 public async Task<UserAccountEntity> LoginTest(UserAccountEntity userAccountEntity)
 {
     var authManager = new AuthenticationManager();
     UserAccountEntity.User user = await authManager.GetUserEntity(userAccountEntity);
     if (user == null) return null;
     userAccountEntity.SetUserEntity(user);
     return userAccountEntity;
 }
Пример #18
0
 public ActionResult LogOff()
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
     logService.LogInDb(User.Identity.Name, LogAction.LogOut);
     return(RedirectToAction("Index", "Home"));
 }
Пример #19
0
 public ActionResult LogOff()
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
     return RedirectToAction("AllWrites", "Post");
 }
 public AuthenticationController(AuthenticationManager authenticationManager)
 {
     this.authenticationManager = authenticationManager;
 }
Пример #21
0
        //
        // GET: /Account/LogOff

        public ActionResult LogOff() {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            return Redirect("/");
        }
Пример #22
0
 public ActionResult UnAuthorized()
 {
     AuthenticationManager.SignOut();
     return(View());
 }
Пример #23
0
        //
        // POST: /Account/LogOff
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public ActionResult LogOff() {
        //    AuthenticationManager.SignOut();
        //    return RedirectToAction("Index", "Home");
        //}

        //[HttpPost]
        //[ValidateAntiForgeryToken]
        public ActionResult LogOff() {
            AuthenticationManager.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
            // AuthenticationManager.SignOut();
            return RedirectToAction("Index", "Home");
        }
Пример #24
0
        /// <summary>
        ///  Get the external login information from weixin provider.
        /// </summary>
        public static async Task <Dictionary <string, string> > GetExternalWeixinLoginInfoAsync(this AuthenticationManager authenticationManager, string expectedXsrf = null)
        {
            AuthenticateContext authenticateContext = new AuthenticateContext(WeixinAuthenticationDefaults.AuthenticationScheme);
            await authenticationManager.AuthenticateAsync(authenticateContext);

            if (authenticateContext.Principal == null || authenticateContext.Properties == null || !authenticateContext.Properties.ContainsKey("LoginProvider"))
            {
                return(null);
            }

            if (expectedXsrf != null)
            {
                if (!authenticateContext.Properties.ContainsKey("XsrfId"))
                {
                    return(null);
                }
                if (authenticateContext.Properties["XsrfId"] != expectedXsrf)
                {
                    return(null);
                }
            }

            var userInfo = authenticateContext.Principal.FindFirst("urn:weixin:user_info");

            if (userInfo == null)
            {
                return(null);
            }

            if (!string.IsNullOrEmpty(userInfo.Value))
            {
                var jObject = JObject.Parse(userInfo.Value);

                Dictionary <string, string> dict = new Dictionary <string, string>();

                foreach (var item in jObject)
                {
                    dict[item.Key] = item.Value?.ToString();
                }

                return(dict);
            }

            return(null);
        }
 public SwitchAccountsCommand(AuthenticationManager authManager)
 {
     _authManager = authManager;
 }
Пример #26
0
 public ActionResult LogOff()
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
     return(RedirectToAction("Login", "Account"));
 }
Пример #27
0
 public async Task<Result> PostData(Uri uri, MultipartContent content, UserAuthenticationEntity userAuthenticationEntity, string language = "ja", bool isMessage = false)
 {
     using (var httpClient = new HttpClient())
     {
         try
         {
             var authenticationManager = new AuthenticationManager();
             Result result = new Result(false, "");
             if (RefreshTime(userAuthenticationEntity.ExpiresInDate))
             {
                 var tokens = await authenticationManager.RefreshAccessToken(userAuthenticationEntity.RefreshToken);
                 result.Tokens = tokens.Tokens;
             }
             if (isMessage)
             {
                 httpClient.DefaultRequestHeaders.Add("User-Agent", "PlayStation Messages App/3.20.23");
             }
             httpClient.DefaultRequestHeaders.Add("Accept-Language", language);
             httpClient.DefaultRequestHeaders.Add("Origin", "http://psapp.dl.playstation.net");
             httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userAuthenticationEntity.AccessToken);
             var response = await httpClient.PostAsync(uri, content);
             var responseContent = await response.Content.ReadAsStringAsync();
             result.IsSuccess = response.IsSuccessStatusCode;
             result.ResultJson = responseContent;
             return result;
         }
         catch
         {
             // TODO: Add detail error result to json object.
             return new Result(false, string.Empty);
         }
     }
 }
Пример #28
0
		private void DetachFromVisualTree()
		{
			if (_authenticationManager != null)
			{
				_authenticationManager.TokenReceived -= AuthenticationManagerOnTokenReceived;
				_authenticationManager.BusyStateChanged -= AuthenticationManagerOnBusyStateChanged;
				_authenticationManager.Dispose();
				_authenticationManager = null;
			}

			if (_webBrowser != null)
			{
				_webBrowser.BeginNavigation -= WebBrowserOnBeginNavigation;
				_webBrowser = null;
			}
		}
Пример #29
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // USED FOR DEBUGGING
            //System.Diagnostics.Trace.TraceError("Before SignIn...{0}", loginInfo);
            //SignInStatus result;
            //// Sign in the user with this external login provider if the user already has a login
            //try
            //{
            //    result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
            //}
            //catch (Exception e)
            //{
            //    System.Diagnostics.Trace.TraceError("Catch SignIn...{0}", e);
            //    throw e;
            //}
            //System.Diagnostics.Trace.TraceError("After SignIn...{0}", result);

            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                var email = loginInfo.Email;

                if (email.Split('@').Last() != "etsmtl.net")
                {
                    return(RedirectToAction(nameof(AccountController.Login), "Account", new { error = "InvalidDomain" }));
                }
                else
                {
                    System.Diagnostics.Trace.TraceError("Before Return...");
                    var firstName = loginInfo.ExternalIdentity.FindFirstValue(ClaimTypes.GivenName);
                    var lastName  = loginInfo.ExternalIdentity.FindFirstValue(ClaimTypes.Surname);
                    return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                        Email = email,
                        FirstName = firstName,
                        LastName = lastName,
                        BarCode = string.Empty
                    }));
                }
            }
        }
Пример #30
0
 public ActionResult LogOff()
 {
     AuthenticationManager.SignOut();
     return(RedirectToAction("Index", "Home"));
 }
        public async Task<Result> SendLoginData(string username, string password)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    // Set the default headers
                    // These are needed so the PSN Auth server will accept our username and password
                    // and hand us a token
                    // If we don't, we will get an HTML page back with no codes

                    httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                    httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13C75 PlayStation Messages App/3.10.67");
                    httpClient.DefaultRequestHeaders.Add("Accept-Language", "ja-jp");
                    httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
                    httpClient.DefaultRequestHeaders.Referrer = new Uri(EndPoints.AuthReferrer);
                    httpClient.DefaultRequestHeaders.Add("Origin", "https://id.sonyentertainmentnetwork.com");

                    var nameValueCollection = new Dictionary<string, string>
                    {
                        {"authentication_type", "password"},
                        {"client_id", EndPoints.LoginKey},
                        {"username", username},
                        {"password", password},
                    };
                    var form = new FormUrlEncodedContent(nameValueCollection);

                    // Send out initial request to get an "SSO Cookie", which is actually in JSON too. For some reason.
                    var response = await httpClient.PostAsync(EndPoints.SsoCookie, form);

                    if (!response.IsSuccessStatusCode)
                    {
                        return ErrorHandler.CreateErrorObject(new Result(), "Username/Password Failed", "Auth");
                    }

                    var responseJson = await response.Content.ReadAsStringAsync();

                    // Get the npsso key. Add the client id, scope, and service entity and send it back.
                    var authorizeCheck = JsonConvert.DeserializeObject<AuthorizeCheck>(responseJson);
                    authorizeCheck.client_id = EndPoints.LoginKey;
                    authorizeCheck.scope = EndPoints.Scope;
                    authorizeCheck.service_entity = "urn:service-entity:psn";

                    var json = JsonConvert.SerializeObject(authorizeCheck);
                    var stringContent = new StringContent(json, Encoding.UTF8, "application/json");

                    // Call auth check so we can continue the flow...
                    await httpClient.PostAsync(EndPoints.AuthorizeCheck, stringContent);

                    // Get our code, so we can get our access tokens.
                    var testResult = await httpClient.GetAsync(new Uri(EndPoints.Login));

                    var codeUrl = testResult.Headers.Location;
                    var queryString = UriExtensions.ParseQueryString(codeUrl.ToString());
                    if (queryString.ContainsKey("authentication_error"))
                    {
                        return ErrorHandler.CreateErrorObject(new Result(), "Failed to get OAuth Code (Authentication_error)", "Auth");
                    }

                    if (!queryString.ContainsKey("code"))
                    {
                        return ErrorHandler.CreateErrorObject(new Result(), "Failed to get OAuth Code (No code)", "Auth");
                    }

                    var authManager = new AuthenticationManager();
                    var authEntity = await authManager.RequestAccessToken(queryString["code"]);
                    return !string.IsNullOrEmpty(authEntity) ? new Result(true, null, authEntity) : new Result(false, null, null);
                }
            }
            catch (Exception ex)
            {
                // All else fails, send back the stack trace.
                return ErrorHandler.CreateErrorObject(new Result(), ex.Message, ex.StackTrace);
            }
        }
Пример #32
0
 public ActionResult LogOff()
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
     return(RedirectToAction("Index", "Home"));
 }
Пример #33
0
        /// <summary>
        /// Grabs the build number of the environment that we're testing
        /// </summary>
        /// <returns>Build number of the environment that's being tested</returns>
        private string GetBuildNumber()
        {
            string build = "";
            try
            {
                AuthenticationManager am = new AuthenticationManager();
                if (testConfiguration.TestAuthentication.AppOnly)
                {
                    string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(testConfiguration.TestSiteUrl));

                    ClientContext ctx = null;

                    if (new Uri(testConfiguration.TestSiteUrl).DnsSafeHost.Contains("spoppe.com"))
                    {
                        ctx = am.GetAppOnlyAuthenticatedContext(testConfiguration.TestSiteUrl, realm, testConfiguration.TestAuthentication.AppId, testConfiguration.TestAuthentication.AppSecret, acsHostUrl: "windows-ppe.net", globalEndPointPrefix: "login");
                    }
                    else
                    {
                        ctx = am.GetAppOnlyAuthenticatedContext(testConfiguration.TestSiteUrl, realm, testConfiguration.TestAuthentication.AppId, testConfiguration.TestAuthentication.AppSecret);
                    }

                    using (ctx)
                    {
                        ctx.Load(ctx.Web, w => w.Title);
                        ctx.ExecuteQueryRetry();
                        build = ctx.ServerLibraryVersion.ToString();
                    }
                }
                else
                {
                    if (!String.IsNullOrEmpty(testConfiguration.TestAuthentication.CredentialManagerLabel))
                    {
                        System.Net.ICredentials credentials = null;

                        if (testConfiguration.TestAuthentication.Type == TestAuthenticationType.OnPremises)
                        {
                            var tempCred = CredentialManager.GetCredential(testConfiguration.TestAuthentication.CredentialManagerLabel);
                            if (tempCred.UserName.IndexOf("\\") > 0)
                            {
                                string[] userParts = tempCred.UserName.Split('\\');
                                credentials = new System.Net.NetworkCredential(userParts[1], tempCred.SecurePassword, userParts[0]);
                            }
                            else
                            {
                                throw new ArgumentException(String.Format("Username {0} stored in credential manager value {1} needs to be formatted as domain\\user", tempCred.UserName, testConfiguration.TestAuthentication.CredentialManagerLabel));
                            }
                        }
                        else
                        {
                            credentials = CredentialManager.GetSharePointOnlineCredential(testConfiguration.TestAuthentication.CredentialManagerLabel);
                        }

                        using (ClientContext ctx = new ClientContext(testConfiguration.TestSiteUrl))
                        {
                            ctx.Credentials = credentials;
                            ctx.Load(ctx.Web, w => w.Title);
                            ctx.ExecuteQueryRetry();
                            build = ctx.ServerLibraryVersion.ToString();
                        }
                    }
                    else
                    {
                        if (testConfiguration.TestAuthentication.Type == TestAuthenticationType.Online)
                        {
                            using (ClientContext ctx = am.GetSharePointOnlineAuthenticatedContextTenant(testConfiguration.TestSiteUrl, testConfiguration.TestAuthentication.User, testConfiguration.TestAuthentication.Password))
                            {
                                ctx.Load(ctx.Web, w => w.Title);
                                ctx.ExecuteQueryRetry();
                                build = ctx.ServerLibraryVersion.ToString();
                            }
                        }
                        else
                        {
                            using (ClientContext ctx = am.GetNetworkCredentialAuthenticatedContext(testConfiguration.TestSiteUrl, testConfiguration.TestAuthentication.User, testConfiguration.TestAuthentication.Password, testConfiguration.TestAuthentication.Domain))
                            {
                                ctx.Load(ctx.Web, w => w.Title);
                                ctx.ExecuteQueryRetry();
                                build = ctx.ServerLibraryVersion.ToString();
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("ERROR: Most likely something is wrong with the provided credentials (username+pwd, appid+secret, credential manager setting) causing the below error:");
                Console.WriteLine(ex.ToString());
                //throw;
            }

            return build;
        }
Пример #34
0
        protected void ReleaseResources()
        {
            if (_authManager != null)
            {
                _authManager.BusyStateChanged -= AuthManagerOnBusyStateChanged;
                _authManager.TokenReceived -= AuthManagerOnTokenReceived;
                _authManager.Dispose();
                _authManager = null;
            }

            if (AuthBrowser != null)
            {
                AuthBrowser.BeginNavigation -= AuthBrowserOnBeginNavigation;
            }
        }
Пример #35
0
        protected void SetupResources()
        {
            _widgetHeight = this.Size.Height;
            _widgetWidth = this.Size.Width;

            AuthBrowser.BeginNavigation += AuthBrowserOnBeginNavigation;

            _authManager = new AuthenticationManager(Resources.EngageHtml);
            _authManager.TokenReceived += AuthManagerOnTokenReceived;
            _authManager.BusyStateChanged += AuthManagerOnBusyStateChanged;
            _authManager.Initialize(this);
        }
Пример #36
0
 public ActionResult signout()
 {
     AuthenticationManager.SignOut();
     return RedirectToAction("Index", "Home");
 }
        public async Task<Result> SendLoginData(string userName, string password)
        {
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B440 Safari/600.1.4");
            httpClient.DefaultRequestHeaders.Add("Accept-Language", "ja-jp");
            httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
            var ohNoTest = await httpClient.GetAsync(new Uri(EndPoints.Login));

            httpClient.DefaultRequestHeaders.Referrer = new Uri("https://auth.api.sonyentertainmentnetwork.com/login.jsp?service_entity=psn&request_theme=liquid");
            httpClient.DefaultRequestHeaders.Add("Origin", "https://auth.api.sonyentertainmentnetwork.com");
            var nameValueCollection = new Dictionary<string, string>
                {
                { "params", "c2VydmljZV9lbnRpdHk9cHNuJnJlcXVlc3RfdGhlbWU9bGlxdWlkJmF1dGhlbnRpY2F0aW9uX2Vycm9yPXRydWU=" },
                { "rememberSignIn", "On" },
                { "j_username", userName },
                { "j_password", password },
            };

            var form = new FormUrlEncodedContent(nameValueCollection);
            var response = await httpClient.PostAsync(EndPoints.LoginPost, form);
            if (!response.IsSuccessStatusCode)
            {
                return new Result(false, null, null);
            }

            ohNoTest = await httpClient.GetAsync(new Uri(EndPoints.Login));
            var codeUrl = ohNoTest.RequestMessage.RequestUri;
            var queryString = UriExtensions.ParseQueryString(codeUrl.ToString());
            if (queryString.ContainsKey("authentication_error"))
            {
                return new Result(false, null, null);
            }
            if (!queryString.ContainsKey("targetUrl")) return new Result(false, null, null);
            queryString = UriExtensions.ParseQueryString(WebUtility.UrlDecode(queryString["targetUrl"]));
            if (!queryString.ContainsKey("code")) return null;

            var authManager = new AuthenticationManager();
            var authEntity = await authManager.RequestAccessToken(queryString["code"]);
            return !string.IsNullOrEmpty(authEntity) ? new Result(true, null, authEntity) : new Result(false, null, null);
        }
Пример #38
0
        /// <summary>
        /// Grabs the build number of the environment that we're testing
        /// </summary>
        /// <returns>Build number of the environment that's being tested</returns>
        private string GetBuildNumber()
        {
            string build;
            try
            {
                AuthenticationManager am = new AuthenticationManager();
                if (testConfiguration.TestAuthentication.AppOnly)
                {
                    string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(testConfiguration.TestSiteUrl));

                    using (ClientContext ctx = am.GetAppOnlyAuthenticatedContext(testConfiguration.TestSiteUrl, realm, testConfiguration.TestAuthentication.AppId, testConfiguration.TestAuthentication.AppSecret))
                    {
                        ctx.Load(ctx.Web, w => w.Title);
                        ctx.ExecuteQueryRetry();
                        build = ctx.ServerLibraryVersion.ToString();
                    }
                }
                else
                {
                    if (!String.IsNullOrEmpty(testConfiguration.TestAuthentication.CredentialManagerLabel))
                    {
                        var credentials = CredentialManager.GetSharePointOnlineCredential(testConfiguration.TestAuthentication.CredentialManagerLabel);
                        using (ClientContext ctx = new ClientContext(testConfiguration.TestSiteUrl))
                        {
                            ctx.Credentials = credentials;
                            ctx.Load(ctx.Web, w => w.Title);
                            ctx.ExecuteQueryRetry();
                            build = ctx.ServerLibraryVersion.ToString();
                        }
                    }
                    else
                    {
                        if (testConfiguration.TestAuthentication.Type == TestAuthenticationType.Online)
                        {
                            using (ClientContext ctx = am.GetSharePointOnlineAuthenticatedContextTenant(testConfiguration.TestSiteUrl, testConfiguration.TestAuthentication.User, testConfiguration.TestAuthentication.Password))
                            {
                                ctx.Load(ctx.Web, w => w.Title);
                                ctx.ExecuteQueryRetry();
                                build = ctx.ServerLibraryVersion.ToString();
                            }
                        }
                        else
                        {
                            using (ClientContext ctx = am.GetNetworkCredentialAuthenticatedContext(testConfiguration.TestSiteUrl, testConfiguration.TestAuthentication.User, testConfiguration.TestAuthentication.Password, testConfiguration.TestAuthentication.Domain))
                            {
                                ctx.Load(ctx.Web, w => w.Title);
                                ctx.ExecuteQueryRetry();
                                build = ctx.ServerLibraryVersion.ToString();
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("ERROR: Most likely something is wrong with the provided credentials (username+pwd, appid+secret, credential manager setting) causing the below error:");
                Console.WriteLine(ex.ToString());
                throw;
            }

            return build;
        }
        public async Task Cookies_Are_Retrieved_Successfully()
        {
            const string expectedUri = "http://fake.forums.somethingawful.com/";

            var cookieContainer = new CookieContainer();
            cookieContainer.Add(new Uri(expectedUri), new Cookie("Foo", "bar"));
            cookieContainer.Add(new Uri(expectedUri), new Cookie("Bar", "Foo"));
            var webManager = new FakeWebManager
            {
                CookiesToReturn = cookieContainer,
            };

            var localStorage = new FakeLocalStorageManager();
            var am = new AuthenticationManager(webManager, localStorage);

            await am.Authenticate("foo", "bar");
            localStorage.CookiesToReturn = localStorage.SavedCookies;

            CookieContainer cookies = await localStorage.LoadCookie(Constants.COOKIE_FILE);

            Assert.AreEqual(2, cookies.Count);
        }
        public async Task Cookies_Are_Stored_Successfully()
        {
            const string expectedUri = "http://fake.forums.somethingawful.com/";

            var cookieContainer = new CookieContainer();
            cookieContainer.Add(new Uri(expectedUri), new Cookie("Foo", "bar"));
            cookieContainer.Add(new Uri(expectedUri), new Cookie("Bar", "Foo"));
            var webManager = new FakeWebManager
            {
                CookiesToReturn = cookieContainer,
            };

            var localStorage = new FakeLocalStorageManager();
            var am = new AuthenticationManager(webManager, localStorage);

            await am.Authenticate("foo", "bar");

            Assert.AreEqual(expectedUri, localStorage.SavedUri.AbsoluteUri);
            Assert.AreEqual(2, localStorage.SavedCookies.Count);
            CookieCollection storedCookies = localStorage.SavedCookies.GetCookies(new Uri(expectedUri));
            Assert.IsNotNull(storedCookies["Foo"]);
            Assert.IsNotNull(storedCookies["Bar"]);
        }
Пример #41
-1
 public async Task<Result> DeleteData(Uri uri, StringContent json, UserAuthenticationEntity userAuthenticationEntity, string language = "ja")
 {
     var handler = new HttpClientHandler
     {
         AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
     };
     using (var httpClient = new HttpClient(handler))
     {
         try
         {
             var authenticationManager = new AuthenticationManager();
             Result result = new Result(false, "");
             if (RefreshTime(userAuthenticationEntity.ExpiresInDate))
             {
                 var tokens = await authenticationManager.RefreshAccessToken(userAuthenticationEntity.RefreshToken);
                 result.Tokens = tokens.Tokens;
             }
             httpClient.DefaultRequestHeaders.Add("Accept-Language", language);
             httpClient.DefaultRequestHeaders.Add("Origin", "http://psapp.dl.playstation.net");
             httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userAuthenticationEntity.AccessToken);
             var response = await httpClient.DeleteAsync(uri);
             var responseContent = await response.Content.ReadAsStringAsync();
             result.IsSuccess = response.IsSuccessStatusCode;
             result.ResultJson = responseContent;
             return result;
         }
         catch (Exception)
         {
             return new Result(false, string.Empty);
         }
     }
 }