Example #1
0
        public IdentityApplicationUser ParseToken(string accessToken)
        {
            if (!string.IsNullOrWhiteSpace(accessToken))
            {
                var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();

                var jwtSecurityToken = jwtSecurityTokenHandler.ReadJwtToken(accessToken);

                var claims = jwtSecurityToken.Claims;

                var appUser = new IdentityApplicationUser
                {
                    Id                   = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject)?.Value ?? "",
                    UserName             = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.PreferredUserName)?.Value ?? "",
                    Email                = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ?? "",
                    EmailConfirmed       = Convert.ToBoolean(claims.FirstOrDefault(x => x.Type == JwtClaimTypes.EmailVerified)?.Value ?? "false"),
                    PhoneNumber          = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.PhoneNumber)?.Value ?? "",
                    PhoneNumberConfirmed = Convert.ToBoolean(claims.FirstOrDefault(x => x.Type == JwtClaimTypes.PhoneNumberVerified)?.Value ?? "false"),
                    LoginAs              = claims.FirstOrDefault(x => x.Type == "LoginAs")?.Value ?? "",
                };
                var roles = claims.Where(s => s.Type == JwtClaimTypes.Role).Select(s => s.Value).ToList();

                appUser.Roles.AddRange(roles);

                return(appUser);
            }
            else
            {
                return(new IdentityApplicationUser());
            }
        }
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    throw new ApplicationException("Error loading external login information during confirmation.");
                }
                var user = new IdentityApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

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

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(nameof(ExternalLogin), model));
        }
Example #3
0
        private async Task LoadSharedKeyAndQrCodeUriAsync(IdentityApplicationUser user, EnableAuthenticatorViewModel model)
        {
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            model.SharedKey        = FormatKey(unformattedKey);
            model.AuthenticatorUri = GenerateQrCodeUri(user.Email, unformattedKey);
        }
        /// <summary>
        /// Осуществляет вход указанного пользователя в систему.
        /// </summary>
        private async Task <PublicUserInfo> SignIn(IdentityApplicationUser user, bool?remember)
        {
            // Выход из системы
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);

            // Создание новых учетных данных
            var identity = await ApplicationUserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            // Вход в систему с новыми учетными данными
            AuthenticationManager.SignIn(new AuthenticationProperties {
                IsPersistent = remember == true
            }, identity);

            var userInfo = BuildPublicUserInfo(user, identity);

            return(userInfo);
        }
Example #5
0
        private async Task CreateRoles(IServiceProvider serviceProvider)
        {
            //adding custom roles
            var RoleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >();
            var UserManager = serviceProvider.GetRequiredService <UserManager <IdentityApplicationUser> >();
            var Context     = serviceProvider.GetRequiredService <ApplicationDbContext>();

            string[]       roleNames = { "Admin", "Moderator", "User" };
            IdentityResult roleResult;

            foreach (var roleName in roleNames)
            {
                //creating the roles and seeding them to the database
                var roleExist = await RoleManager.RoleExistsAsync(roleName);

                if (!roleExist)
                {
                    roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
                }
            }

            var powerUser = new IdentityApplicationUser
            {
                UserName = Configuration.GetSection("UserSettings")["UserName"],
                Email    = Configuration.GetSection("UserSettings")["UserEmail"]
            };
            string userPassword = Configuration.GetSection("UserSettings")["UserPassword"];
            var    _user        = await UserManager.FindByEmailAsync(Configuration.GetSection("UserSettings")["UserEmail"]);

            if (_user == null)
            {
                var createPowerUser = await UserManager.CreateAsync(powerUser, userPassword);

                Context.MainUsers.Add(new MainUser
                {
                    IdentityUserId = powerUser.Id,
                    AvatarPath     = "Default",
                    Username       = "******"
                });

                if (createPowerUser.Succeeded)
                {
                    await UserManager.AddToRoleAsync(powerUser, "Admin");
                }
            }
        }
Example #6
0
        protected async Task <Mutation> CreateNewUser()
        {
            lastEmailUsed = Guid.NewGuid() + "@test.com";
            var query = new MutationQueryBuilder().WithCreateUser(
                new IdentityResponseQueryBuilder()
                .WithToken()
                .WithUser(new IdentityApplicationUserQueryBuilder().WithId().WithEmail()),
                new CreateUserRequestInput
            {
                BirthDate   = "2020-01-01",
                Name        = "Mads",
                Email       = lastEmailUsed,
                PhoneNumber = "12345678",
                Password    = "******"
            })
                        .Build();

            var result = await Mutate(query);

            lastestUser = result.CreateUser.User;
            return(result);
        }
        /// <summary>
        /// Создает учетную запись пользователя по информации внешнего провайдера.
        /// </summary>
        private static IdentityApplicationUser CreateUserByLoginInfo(ExternalLoginInfo loginInfo)
        {
            var userName = loginInfo.DefaultUserName;

            if (loginInfo.Login != null)
            {
                userName = $"{loginInfo.Login.LoginProvider}{loginInfo.Login.ProviderKey}".Replace(" ", string.Empty);
            }

            var user = new IdentityApplicationUser
            {
                Id             = Guid.NewGuid().ToString(),
                UserName       = userName,
                Email          = loginInfo.Email,
                EmailConfirmed = !string.IsNullOrWhiteSpace(loginInfo.Email)
            };

            if (loginInfo.ExternalIdentity?.Claims != null)
            {
                user.Claims = loginInfo.ExternalIdentity.Claims.Select(CreateUserClaim);
            }

            return(user);
        }
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                if (_userManager.Users.Any(x => x.UserName.ToLower() == model.Username.ToLower()))
                {
                    ModelState.AddModelError(string.Empty, "This username is taken, username must be unique");
                    return(View(model));
                }

                string uploadDir = Path.Combine(_environment.WebRootPath, "Avatars");
                string filePath  = "Default";

                if (model.AvatarImage != null)
                {
                    var userDir = Path.Combine(uploadDir, model.Username);
                    Directory.CreateDirectory(userDir);
                    var uploadTemp = Path.Combine(uploadDir, userDir, model.AvatarImage.FileName);
                    filePath = Path.Combine(uploadDir, userDir);
                    using (var stream = new FileStream(uploadTemp, FileMode.Create))
                    {
                        model.AvatarImage.CopyTo(stream);
                    }
                }

                var identityUser = new IdentityApplicationUser {
                    UserName = model.Username, Email = model.Email
                };
                var user = new MainUser {
                    Username   = identityUser.UserName, IdentityUserId = identityUser.Id,
                    AvatarPath = filePath
                };

                _context.MainUsers.Add(user);
                try
                {
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    return(View(model));
                }

                var result = await _userManager.CreateAsync(identityUser, model.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    await _userManager.AddToRoleAsync(identityUser, "User");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(identityUser);

                    var callbackUrl = Url.EmailConfirmationLink(identityUser.Id, code, Request.Scheme);
                    await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

                    await _signInManager.SignInAsync(identityUser, isPersistent : false);

                    _logger.LogInformation("User created a new account with password.");
                    return(RedirectToLocal(returnUrl));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }