private async static Task AddApplicationAdmin(IConfiguration config, UserManager <IdentityAppUser> userManager, RoleManager <IdentityAppRole> roleManager) { IdentityAppUser explorerAdmin = config.GetSection(nameof(IdentityAppUser)).Get <IdentityAppUser>(); var adminTask = await userManager.Users.AllAsync(u => u.UserName != explorerAdmin.UserName); var roleTask = await roleManager.Roles.FirstOrDefaultAsync(r => r.Name == Role.ADMIN); if (!adminTask) { return; } explorerAdmin.UserRoles.Add(new IdentityAppUserRole { Role = roleTask }); IdentityResult result = await userManager.CreateAsync(explorerAdmin, nameof(explorerAdmin)); var claims = new Claim[] { new Claim(ClaimTypes.NameIdentifier, explorerAdmin.Id.ToString()), new Claim(ClaimTypes.Role, roleTask.Name) }; await userManager.AddClaimsAsync(explorerAdmin, claims); if (!result.Succeeded) { throw new Exception("Admin seed exception"); } }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (ModelState.IsValid) { var user = new IdentityAppUser(IdentityAppUser.GenerateUsername(Input.Email), Input.Email); var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); // If account confirmation is required, we need to show the link if we don't have a real email sender if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email })); } await _signInManager.SignInAsync(user, isPersistent : false); var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } LoginProvider = info.LoginProvider; ReturnUrl = returnUrl; return(Page()); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new IdentityAppUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); //Code deve ser enviado por email juntamente com o Link, onde o usuário poderá confirmar o e-mail await _userManager.SendEmailAsync(user.Id, "Confirme sua Conta", "Por favor confirme sua conta clicando neste link: <a href='" + callbackUrl + "'></a>"); ViewBag.Link = callbackUrl; return(View("DisplayEmail")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public static void SeedUser(this IApplicationBuilder app) { using var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope(); var context = serviceScope.ServiceProvider.GetRequiredService <IdentityDBContext>(); if (!context.Users.Any(_ => _.Email == "*****@*****.**")) { var userManager = serviceScope.ServiceProvider.GetRequiredService <UserManager <IdentityAppUser> >(); var user = new IdentityAppUser("devadmin", "*****@*****.**", "Milton", "Friedman"); var result = userManager.CreateAsync(user, "Dev321").Result; if (result.Succeeded) { var roleName = RolesEnum.DEBUG.GetDescription(); var roleManager = serviceScope.ServiceProvider.GetRequiredService <RoleManager <ApplicationRole> >(); _ = roleManager.CreateAsync(new ApplicationRole(roleName, "For development porpouse")).Result; user = userManager.FindByNameAsync("devadmin").Result; var roleResul = userManager.AddToRoleAsync(user, roleName).Result; } } }
public async Task <AuthResult <Token> > RefreshToken(RefreshTokenDTO refreshTokenDto) { var refreshToken = refreshTokenDto?.Token?.Refresh_token; if (string.IsNullOrEmpty(refreshToken)) { return(AuthResult <Token> .UnvalidatedResult); } try { //var principal = JwtManager.GetPrincipal(refreshToken, isAccessToken: false); //int.TryParse(principal.Identity.GetUserId(), out var currentUserId); var user = new IdentityAppUser(); //await _userManager.FindByIdAsync(currentUserId); JwtSecurityToken if (user != null && !string.IsNullOrEmpty(user.Id) && !user.Deleted) { var token = new Token();// JwtManager.GenerateToken(await _userManager.CreateIdentityAsync(user)); return(await Task.FromResult(AuthResult <Token> .TokenResult(token))); } } catch (Exception) { return(AuthResult <Token> .UnauthorizedResult); } return(AuthResult <Token> .UnauthorizedResult); }
private async Task LoadAsync(IdentityAppUser user) { var userName = await _userManager.GetUserNameAsync(user); var phoneNumber = await _userManager.GetPhoneNumberAsync(user); Username = userName; Input = new InputModel { PhoneNumber = phoneNumber }; }
private async Task LoadAsync(IdentityAppUser user) { var email = await _userManager.GetEmailAsync(user); Email = email; Input = new InputModel { NewEmail = email, }; IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user); }
/// <summary> /// Create claim for selected user /// </summary> /// <param name="user">User</param> /// <param name="roleName">role we want to add to claims</param> /// <returns>Array of Claims</returns> private Claim[] CreateClaims(IdentityAppUser user, string roleName) { _log.LogInformation("Generating claims for user {@user}", user); var claims = new Claim[] { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.GivenName, user.UserName), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.Role, roleName), }; return(claims); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = new IdentityAppUser(IdentityAppUser.GenerateUsername(Input.Email), Input.Email); var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email })); } else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
private async Task LoadSharedKeyAndQrCodeUriAsync(IdentityAppUser user) { // Load the authenticator key & QR code URI to display on the form var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); if (string.IsNullOrEmpty(unformattedKey)) { await _userManager.ResetAuthenticatorKeyAsync(user); unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); } SharedKey = FormatKey(unformattedKey); var email = await _userManager.GetEmailAsync(user); AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey); }
public async Task <object> Register([FromBody] RegisterDTO model) { var user = new IdentityAppUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); return(await GenerateJwtToken(model.Email, user)); } throw new ApplicationException("UNKNOWN_ERROR"); }
/// <summary> /// Normal user registration procedure /// </summary> /// <param name="username">username</param> /// <param name="email">email</param> /// <param name="password">password</param> /// <param name="profileImage">profileImagePath</param> /// <returns>Instance of IResult and IUser</returns> public async Task <(Result, IProcessExplorerUser)> RegisterUser(string username, string email, string password, string profileImage) { //Value cant be null var userRole = await GetDefaultRole(); _log.LogInformation($"User registration started"); //start code transaction using var transaction = await _context.Database.BeginTransactionAsync(); try //transaction code { //create IdentityAppUser instance and add default IdentityAppUserRole role to him var newUser = new IdentityAppUser { Email = email, UserName = username }; newUser.UserRoles.Add(new IdentityAppUserRole { Role = userRole }); //Try to add IdentityAppUser to database var identityResultUser = await _userManager.CreateAsync(newUser, password); //Check status of previous operation if (!identityResultUser.Succeeded) { await transaction.RollbackAsync(); return(identityResultUser.GetApplicationResult(), null); } //create claims add add claims to created user var claims = CreateClaims(newUser, userRole.Name); var identityResultClaim = await _userManager.AddClaimsAsync(newUser, claims); //Check status of previous operation if (!identityResultClaim.Succeeded) { //failed to create claims for user await transaction.RollbackAsync(); return(identityResultClaim.GetApplicationResult(), null); } //Create new ProcessExplorerUser instance and add it to database var user = new ProcessExplorerUser(newUser.Id, newUser.Email, newUser.UserName); _work.User.Add(user); await _work.CommitAsync(); //commit transaction await transaction.CommitAsync(); _log.LogInformation("User registration finished {@user}", user); return(Result.Success(), user); } catch (Exception e) // if transaction fails { await transaction.RollbackAsync(); _log.LogError(e, "Transaction error"); return(Result.Failure("Ann error occurred"), null); } }
private async Task <IdentityAppUser> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable <Claim> claims) { // create a list of claims that we want to transfer into our store var filtered = new List <Claim>(); string first = string.Empty; string last = string.Empty; // user's display name var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value; if (name != null) { filtered.Add(new Claim(JwtClaimTypes.Name, name)); } else { first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value; last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value; if (first != null && last != null) { filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last)); } else if (first != null) { filtered.Add(new Claim(JwtClaimTypes.Name, first)); } else if (last != null) { filtered.Add(new Claim(JwtClaimTypes.Name, last)); } } // email var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value; if (email != null) { filtered.Add(new Claim(JwtClaimTypes.Email, email)); } // Modify the user auto-provisioning process depending on how many properties you'd added into <Model.Entities.IdentityAppUser> var user = new IdentityAppUser(pUsername: Guid.NewGuid().ToString(), pEmail: email, first, last);//TODO: get full name if possible var identityResult = await _userManager.CreateAsync(user); if (!identityResult.Succeeded) { throw new Exception(identityResult.Errors.First().Description); } if (filtered.Any()) { identityResult = await _userManager.AddClaimsAsync(user, filtered); if (!identityResult.Succeeded) { throw new Exception(identityResult.Errors.First().Description); } } identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider)); if (!identityResult.Succeeded) { throw new Exception(identityResult.Errors.First().Description); } return(user); }
public static async Task SeedAsync(UserManager <IdentityAppUser> userManager, AppDbContext appDbContext) { Random rnd = new Random(); if (!appDbContext.EmosUsers.Any(u => u.Identity.Email == "*****@*****.**")) { try { var userIdentity = new IdentityAppUser { UserName = "******", Email = "*****@*****.**", FirstName = "Admin", LastName = "Admin", }; await userManager.CreateAsync(userIdentity, "password"); await appDbContext.EmosUsers.AddAsync(new EmosUser { IdentityId = userIdentity.Id, FirstName = userIdentity.FirstName, LastName = userIdentity.LastName, //Service = "Mécanique", //Office = "13", //Team = "Bests", //Rank = "Top", //BadgeCode = rnd.Next(1,9).ToString() }); IdentityAppUser[] identityUsers = new IdentityAppUser[120]; for (int i = 1; i < 120; i++) { identityUsers[i] = new IdentityAppUser { UserName = $"user{i}@lgm.fr", Email = $"user{i}@lgm.fr", FirstName = $"prenom{i}", LastName = $"nom{i}", }; await userManager.CreateAsync(identityUsers[i], "password"); appDbContext.EmosUsers.Add(new EmosUser { IdentityId = identityUsers[i].Id, FirstName = identityUsers[i].FirstName, LastName = identityUsers[i].LastName, //Service = $"Service{i%5}", //Office = $"bureau{i%5}", //Team = $"Equipe{i%10}", //Rank = $"Grade{i%4}", //BadgeCode = rnd.Next(1, 9).ToString() }); appDbContext.SaveChanges(); } } catch { } } }