Exemplo n.º 1
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                // AAD
                var authResult = await AuthenticationManager.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationType);

                loginInfo = GetExternalLoginInfo(authResult);
            }

            return(RedirectToLocal(returnUrl));

            //// Sign in the user with this external login provider if the user already has a login
            //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;
            //        return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
            //}
        }
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);


            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

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

            // Sign in the user with this external login provider if the user already has a login
            var user = await UserManager.FindAsync(loginInfo.Login);

            if (user != null)
            {
                await SignInAsync(user, isPersistent : false);

                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    UserName = loginInfo.DefaultUserName
                }));
            }
        }
        public async Task <ActionResult> ExternalLoginCallback()
        {
            var authenticateResult = await AuthenticationManager.AuthenticateAsync("ExternalCookie");

            if (authenticateResult != null)
            {
                string userEmail = authenticateResult.Identity.Claims.Where(c => c.Type == ClaimTypes.Email).Select(c => c.Value).SingleOrDefault();

                if (userEmail != null)
                {
                    for (int x = 0; x < approvedUsers.Length; x++)
                    {
                        if (userEmail.ToString() == approvedUsers[x])
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                    AuthenticationManager.SignOut();
                    return(RedirectToAction("ErrorBadLogin", "Home"));
                }
                else
                {
                    return(RedirectToAction("ErrorBadLogin", "Home"));
                }
            }
            else
            {
                return(RedirectToAction("ErrorBadLogin", "Home"));
            }
        }
Exemplo n.º 4
0
        public static async Task <string> GetAccessTokenAsync(this AuthenticationManager manager)
        {
            var context = new AuthenticateContext("Cookies");
            await manager.AuthenticateAsync(context);

            return(context.Properties[".Token.access_token"]);
        }
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

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


            var identity = AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie).Result.Identity;

            if (identity != null)
            {
                AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                AuthenticationManager.SignIn(
                    new AuthenticationProperties {
                    IsPersistent = true
                },
                    new ClaimsIdentity(identity.Claims, "Application", identity.NameClaimType, identity.RoleClaimType));
            }

            // If the user does not have an account, then prompt the user to create an account
            ViewBag.ReturnUrl     = returnUrl;
            ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
            return(View("uaepass", MyGlobalVariables.GlobalUser));
        }
        public virtual async Task <int?> GetVerifiedTenantIdAsync()
        {
            var authenticateResult = await AuthenticationManager.AuthenticateAsync(
                DefaultAuthenticationTypes.TwoFactorCookie
                );

            return(authenticateResult?.Identity?.GetTenantId());
        }
Exemplo n.º 7
0
        public async Task <Guid> GetVerifiedUserIdGuidAsync()
        {
            var result =
                await
                AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.TwoFactorCookie)
                .WithCurrentCulture();

            return(result?.Identity == null ? default(Guid) : Guid.Parse(result.Identity.GetUserId()));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Get the user id that has been verified already or null.
        /// </summary>
        /// <returns></returns>
        public async Task <string> GetVerifiedUserIdAsync()
        {
            var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.TwoFactorCookie);

            if (result != null && result.Identity != null && !String.IsNullOrEmpty(result.Identity.GetUserId()))
            {
                return(result.Identity.GetUserId());
            }
            return("");
        }
Exemplo n.º 9
0
        private async Task <int?> GetTwoFactorLoginUserIdAsync()
        {
            var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.TwoFactorCookie);

            if (result?.Identity != null && !string.IsNullOrEmpty(result.Identity.GetUserId()))
            {
                return(result.Identity.GetId());
            }
            return(null);
        }
        /// <summary>
        /// Get the user id that has been verified already or -1.
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// Replaces the underlying call which is not flexible and doesn't support a custom cookie
        /// </remarks>
        public new async Task <int> GetVerifiedUserIdAsync()
        {
            var result = await AuthenticationManager.AuthenticateAsync(Constants.Security.BackOfficeTwoFactorAuthenticationType);

            if (result != null && result.Identity != null && string.IsNullOrEmpty(result.Identity.GetUserId()) == false)
            {
                return(ConvertIdFromString(result.Identity.GetUserId()));
            }
            return(-1);
        }
        /// <summary>
        /// Get the username that has been verified already or null.
        /// </summary>
        /// <returns></returns>
        public async Task <string> GetVerifiedUserNameAsync()
        {
            var result = await AuthenticationManager.AuthenticateAsync(Constants.Security.BackOfficeTwoFactorAuthenticationType);

            if (result != null && result.Identity != null && string.IsNullOrEmpty(result.Identity.GetUserName()) == false)
            {
                return(result.Identity.GetUserName());
            }
            return(null);
        }
Exemplo n.º 12
0
        public async Task LoginUserWithPassword()
        {
            IsLoading = true;
            await RemoveUserCookies();

            var result = await _authenticationManager.AuthenticateAsync(Username, Password);

            if (!result.IsSuccess)
            {
                await ResultChecker.SendMessageDialogAsync(result.Error, false);

                IsLoading = false;
                return;
            }

            WebManager = new WebClient(result.AuthenticationCookieContainer);

            var userManager = new UserManager(WebManager);

            // 0 gets us the default user.
            var userResult = await userManager.GetUserFromProfilePageAsync(0);

            if (userResult == null)
            {
                await ResultChecker.SendMessageDialogAsync("Failed to get user", false);

                IsLoading = false;
                return;
            }

            try
            {
                var newUser = new UserAuth {
                    AvatarLink = userResult.AvatarLink, IsDefaultUser = true, UserName = userResult.Username, CookiePath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, Guid.NewGuid().ToString() + ".cookie")
                };
                await UserAuthDatabase.AddOrUpdateUser(newUser);

                CookieManager.SaveCookie(result.AuthenticationCookieContainer, newUser.CookiePath);
            }
            catch (Exception ex)
            {
                await ResultChecker.SendMessageDialogAsync($"Failed to save user: {ex.Message}", false);

                IsLoading = false;
                return;
            }

            IsLoading  = false;
            IsLoggedIn = true;

            App.ShellViewModel.PopulateNavItems();
            NavigationService.Navigate(typeof(Views.MainPage));
        }
Exemplo n.º 13
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                var extendedInfo = AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }

                var user = new ApplicationUser {
                    UserName = model.Email,
                    Email    = model.Email,
                    Picture  = new ProfilePicture {
                        URL = "~/Images/Users/defaultAvatar.png"
                    }
                };

                var result = await UserManager.CreateAsync(user);

                await UserManager.AddToRoleAsync(user.Id, "customer");

                await UserManager.AddClaimAsync(user.Id, new Claim("ProfilePicture", user.Picture.URL));

                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

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

                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
Exemplo n.º 14
0
        //
        // GET: /Manage/LinkLoginCallback
        public async Task <ActionResult> LinkLoginCallback()
        {
            //Método muito monstro para receber algumas informações Third-Party.
            var authenticateResult = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());

            if (loginInfo == null)
            {
                return(RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }));
            }
            var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);

            return(result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }));
        }
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            // no - it simplifies it
            // var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            var result = await AuthenticationManager.AuthenticateAsync("ExternalCookie");

            var emailClaim = result.Identity.Claims.FirstOrDefault(
                c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress");
            var email = emailClaim != null ? emailClaim.Value : "";

            ExternalLoginInfo loginInfo = null;
            Claim             nameClaim = result.Identity.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier");

            if (nameClaim != null)
            {
                string str = result.Identity.Name.Replace(" ", "");
                loginInfo = new ExternalLoginInfo()
                {
                    Login           = new UserLoginInfo(nameClaim.Issuer, nameClaim.Value),
                    DefaultUserName = str
                };
            }

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

            // Sign in the user with this external login provider if the user already has a login
            var user = await UserManager.FindAsync(loginInfo.Login);

            if (user != null)
            {
                await SignInAsync(user, isPersistent : false);

                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    UserName = loginInfo.DefaultUserName
                }));
            }
        }
Exemplo n.º 16
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            logger.Debug("ExternalLoginCallback:" + returnUrl);
            var loginInfo = await AuthenticationManager_GetExternalLoginInfoAsync_Workaround();//AuthenticationManager.GetExternalLoginInfoAsync();

            logger.Debug(new { loginInfo = loginInfo });


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

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            var nresult = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

            logger.Debug(
                new {
                ResultFromCallback = result,
                ReturnUrl          = returnUrl,
                Claims             = nresult.Identity.Claims,
                loginInfo          = loginInfo
            });


            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;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email
                }));
            }
        }
Exemplo n.º 17
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var info = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

            var claims = "";

            foreach (var claim in info.Identity.Claims)
            {
                claims += claim.ToString() + "\n";
            }

            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

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

            // Sign in the user with this external login provider if the user already has a login
            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;
                return(View(
                           "ExternalLoginConfirmation",
                           new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email,
                    FirstName = loginInfo.DefaultUserName,
                    LastName = loginInfo.DefaultUserName,
                    Claims = claims
                }));
            }
        }
Exemplo n.º 18
0
        /// <summary>
        ///  Get the external login information from qq provider.
        /// </summary>
        public static async Task <Dictionary <string, string> > GetExternalQQLoginInfoAsync(this AuthenticationManager authenticationManager, string expectedXsrf = null)
        {
            AuthenticateContext authenticateContext = new AuthenticateContext(QQAuthenticationDefaults.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:qq: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);
        }
Exemplo n.º 19
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie).ConfigureAwait(false);

            if (result == null || result.Identity == null)
            {
                return(RedirectToAction("Login"));
            }

            var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);

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

            var login = new UserLoginInfo(idClaim.Issuer, idClaim.Value);

            // Si el usuario ya tiene una cuenta, autenticarlo con su cuenta de red social
            var user = await UserManager.FindAsync(login).ConfigureAwait(false);

            if (user != null)
            {
                await SignInAsync(user, isPersistent : false);

                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // Si el usuario no tiene una cuenta se le crea y se le invita a compeltar su perfil, redireccionandolo
                //a la pantalla de profile
                try
                {
                    user = _authenticationService.CreateUserWithSocialProvider(login, result.Identity);
                    await SignInAsync(user, isPersistent : false).ConfigureAwait(false);

                    return(RedirectToAction("Profile", new { returnUrl }));
                }
                catch (Exception ex)
                {
                    Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                    throw;
                }
            }
        }
Exemplo n.º 20
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            var vkClaimCookies = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new ApplicationUser()
                {
                    UserName = model.UserName
                };
                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    var vkClaim = vkClaimCookies.Identity.FindFirst("VKAccessToken");
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

                    if (result.Succeeded)
                    {
                        var vkAuthService = new VkAuthService();
                        vkAuthService.CreateOrUpdateUserAccessToken(vkClaim.Value, user.Id);

                        await SignInAsync(user, isPersistent : false);

                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
Exemplo n.º 21
0
        public async Task <ClaimsPrincipal> SignInFromExternalCookieAsync()
        {
            var externalLoginInfo =
                await
                AuthenticationManager.AuthenticateAsync(IdentityOptions.Cookies.ExternalCookieAuthenticationScheme);

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

            // the new schame to replace the old one
            var newScheme = IdentityOptions.Cookies.ApplicationCookieAuthenticationScheme;

            await AuthenticationManager.SignInAsync(newScheme, externalLoginInfo.CloneAs(newScheme));

            return(externalLoginInfo);
        }
Exemplo n.º 22
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var req    = Request;
            var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (result == null || result.Identity == null)
            {
                return(RedirectToAction("Login"));
            }

            var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);

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

            var login = new UserLoginInfo(idClaim.Issuer, idClaim.Value);
            var name  = result.Identity.Name == null ? "" : result.Identity.Name.Replace(" ", "");

            // Sign in the user with this external login provider if the user already has a login
            var user = await UserManager.FindAsync(login);

            if (user != null)
            {
                var vkClaim = result.Identity.FindFirst("VKAccessToken");

                var vkAuthService = new VkAuthService();
                vkAuthService.CreateOrUpdateUserAccessToken(vkClaim.Value, user.Id);

                await SignInAsync(user, isPersistent : false);

                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    UserName = name
                }));
            }
        }
Exemplo n.º 23
0
        private async Task <ExternalLoginInfo> AuthenticationManager_GetExternalLoginInfoAsync_Workaround()
        {
            ExternalLoginInfo loginInfo = null;
            var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (result != null && result.Identity != null)
            {
                var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);
                if (idClaim != null)
                {
                    loginInfo = new ExternalLoginInfo()
                    {
                        DefaultUserName = result.Identity.Name == null ? "" : result.Identity.Name.Replace(" ", ""),
                        Login           = new UserLoginInfo(idClaim.Issuer, idClaim.Value)
                    };
                }
            }
            return(loginInfo);
        }
Exemplo n.º 24
0
        public static async Task <string> GetTokenAsync(this AuthenticationManager manager, string signInScheme, string tokenName)
        {
            if (manager == null)
            {
                throw new ArgumentNullException(nameof(manager));
            }
            if (signInScheme == null)
            {
                throw new ArgumentNullException(nameof(signInScheme));
            }
            if (tokenName == null)
            {
                throw new ArgumentNullException(nameof(tokenName));
            }

            var authContext = new AuthenticateContext(signInScheme);
            await manager.AuthenticateAsync(authContext);

            return(new AuthenticationProperties(authContext.Properties).GetTokenValue(tokenName));
        }
Exemplo n.º 25
0
        public async Task <string> AuthenticateAsync(IUnitOfWork unitOfWork, string email, string password)
        {
            var user = await AuthenticationManager.AuthenticateAsync(unitOfWork, email, password);

            var tokenHandler    = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, user.UserId.ToString()),
                    new Claim(ClaimTypes.Role, user.AccessLevel.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(_daysToExpire),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(_key),
                    SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Exemplo n.º 26
0
        public static async Task <WebClient> SetupWebClient(bool useAuth = true)
        {
            var username = Environment.GetEnvironmentVariable("AWFUL_USER");
            var password = Environment.GetEnvironmentVariable("AWFUL_PASSWORD");

            if (!File.Exists("user.cookies"))
            {
                var WebClient = new WebClient();
                if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
                {
                    return(WebClient);
                }
                var authManager = new AuthenticationManager(WebClient);
                var result      = await authManager.AuthenticateAsync(username, password);

                if (!result.IsSuccess)
                {
                    throw new Exception("Could not log in!");
                }
                using (FileStream stream = File.Create("user.cookies"))
                {
                    var formatter = new BinaryFormatter();
                    System.Console.WriteLine("Serializing cookie container");
                    formatter.Serialize(stream, WebClient.CookieContainer);
                }

                return(WebClient);
            }
            else
            {
                System.Net.CookieContainer cookieContainer;
                using (FileStream stream = File.OpenRead("user.cookies"))
                {
                    var formatter = new BinaryFormatter();
                    System.Console.WriteLine("Deserializing cookie container");
                    cookieContainer = (System.Net.CookieContainer)formatter.Deserialize(stream);
                    return(new WebClient(cookieContainer));
                }
            }
        }
Exemplo n.º 27
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (result == null || result.Identity == null)
            {
                return(RedirectToAction("Login"));
            }

            var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);

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

            var login = new UserLoginInfo(idClaim.Issuer, idClaim.Value);
            var name  = result.Identity.Name == null ? "" : result.Identity.Name.Replace(" ", "");

            // Sign in the user with this external login provider if the user already has a login
            var user = await _userManager.FindAsync(login);

            if (user != null)
            {
                await SignInAsync(user, isPersistent : false);

                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // If the user does not have an account, then prompt the user to create an account

                /*ViewBag.ReturnUrl = returnUrl;
                 * ViewBag.LoginProvider = login.LoginProvider;
                 * return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { UserName = name });*/
                return(View("ExternalLoginFailure", new ExternalLoginFailureViewModel {
                    Message = "Please make an account in the mobile app to login"
                }));
            }
        }
Exemplo n.º 28
0
        private async Task <ExternalLoginInfo> GetExternalLoginInfoWorkaroundAsync()
        {
            ExternalLoginInfo loginInfo = null;

            var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (result == null)
            {
                Log.Error("AuthenticationManager.AuthenticateAsync returned null.", String.Empty);
            }
            else
            {
                if (result.Identity == null)
                {
                    Log.Error("result.Identity is null.", String.Empty);
                }
            }

            if (result != null && result.Identity != null)
            {
                var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);
                if (idClaim != null)
                {
                    var emailClaim = result.Identity.FindFirst(ClaimTypes.Email);

                    loginInfo = new ExternalLoginInfo()
                    {
                        DefaultUserName = result.Identity.Name == null ? "" : result.Identity.Name.Replace(" ", ""),
                        Login           = new UserLoginInfo(idClaim.Issuer, idClaim.Value),
                        Email           = emailClaim != null ? emailClaim.Value : String.Empty
                    };
                }
                else
                {
                    Log.Error("result.Identity.FindFirst(ClaimTypes.NameIdentifier) returned null", String.Empty);
                }
            }
            return(loginInfo);
        }
Exemplo n.º 29
0
        public ActionResult Authorize(AuthorizeViewModel model, bool isGrant)
        {
            if (Response.StatusCode != 200)
            {
                return(View("AuthorizeError"));
            }

            if (ModelState.IsValid)
            {
                var scopes = model.Scope.Split(',');

                if (isGrant)
                {
                    var ticket   = AuthenticationManager.AuthenticateAsync(User.Identity.AuthenticationType).Result;
                    var identity = ticket != null ? ticket.Identity : null;
                    if (identity == null)
                    {
                        return(View("AuthorizeError"));
                    }
                    var oauthIdentity = identity;
                    if (!identity.AuthenticationType.Equals(OAuthDefaults.AuthenticationType, StringComparison.Ordinal))
                    {
                        oauthIdentity = new ClaimsIdentity(identity.Claims, OAuthDefaults.AuthenticationType, identity.NameClaimType, identity.RoleClaimType);
                    }
                    foreach (var scope in scopes)
                    {
                        oauthIdentity.AddClaim(new Claim("urn:oauth:scope", scope, oauthIdentity.AuthenticationType));
                    }
                    AuthenticationManager.SignIn(identity);
                }
                else
                {
                    AuthenticationManager.SignOut();
                    AuthenticationManager.Challenge();
                    return(new HttpUnauthorizedResult());
                }
            }
            return(View());
        }
Exemplo n.º 30
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            try
            {
                ExternalLoginInfo LoginEx = null;
                var VarExternalLogin      = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

                if (VarExternalLogin == null)
                {
                    return(RedirectToAction("Register"));
                }
                //  AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

                var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (VarExternalLogin != null && VarExternalLogin.Identity != null)
                {
                    var idClaim = VarExternalLogin.Identity.FindFirst(ClaimTypes.NameIdentifier);
                }
                else
                {
                    return(RedirectToAction("Register"));
                }


                Session["EmailId"]       = loginInfo.Email;
                Session["ExternalLogin"] = "******";


                ViewBag.LoginProvider = "Welcome";
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email
                }));
            }
            catch (SystemException ex)
            {
                return(RedirectToAction("Register"));
            }
        }