Comments (9)
Fixed the bug, please see commit history. You also have to call userman.UpdateAsync()
after assigning user to a role.
There is another very important thing that you need to be attentive to, the IdentityRole.Id
property gets only assigned from the constructor function, so you have to create roles by passing in the role name into the constructor, new IdentityRole("Admin")
. I'll fix it later, but for now please create roles this way.
var newRole = new IdentityRole("Admin");
var result = await roleman.CreateAsync(newRole);
if (result.Succeeded)
{
var user = new ApplicationUser();
user.UserName = "jos";
user.Email = "******";
string userPWD = "******";
var res= await userman.CreateAsync(user, userPWD);
if (res.Succeeded)
{
var added=await userman.AddToRoleAsync(user, "Admin");
await userman.UpdateAsync(user);
}
Install the new version of the package 1.3.28. I added a few unit tests, and I'll be adding more so you could refer to them as well if you run into issues.
from aspnetcore.identity.ravendb.
yup, gets saved in raven at least.
cant login with the created user though.
(invalid login attempt)
from aspnetcore.identity.ravendb.
I didn't notice you were using the actual UserManager
and not UserStore
. In this case you don't have to call userman.UpdateAsync(user)
, my bad.
Just tested creating of a user and logging-in in a basic AspNet Core application with authentication and it worked.
How are you authenticating the user? Post the code of your login controller route.
from aspnetcore.identity.ravendb.
login controller :
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IOptions<IdentityCookieOptions> identityCookieOptions,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_externalCookieScheme = identityCookieOptions.Value.ExternalCookieAuthenticationScheme;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
//
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl = null)
{
// Clear the existing external cookie to ensure a clean login process
await HttpContext.Authentication.SignOutAsync(_externalCookieScheme);
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
from aspnetcore.identity.ravendb.
I don't see anything unusual, I tested the exact same controller. How are you creating the user?
I used this method and all worked,
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
from aspnetcore.identity.ravendb.
the user is created at startup.
here is my full startup.cs
i did notice however that the user is created again each time the application starts.
still, with just one user present in the applicationusers index, login fails
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using try3.Models;
using try3.Services;
using Maqduni.AspNetCore.Identity.RavenDb;
using Maqduni.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Identity;
namespace try3
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets<Startup>();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddRavenDbAsyncSession(Configuration.GetConnectionString("RavenDb"));
services.AddIdentity<ApplicationUser, Maqduni.AspNetCore.Identity.RavenDb.IdentityRole>(
options =>
{
options.Password.RequireDigit = false;
options.Password.RequiredLength = 6;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = true;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@";
options.User.RequireUniqueEmail = true;
})
.AddRavenDbStores()
.AddDefaultTokenProviders();
services.AddOptions();
services.Configure<TicketSaleConfig>(Configuration.GetSection("TicketSale"));
services.Configure<MultiSafePayConfig>(Configuration.GetSection("MultiSafePay"));
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, RoleManager<IdentityRole> roleman, UserManager<ApplicationUser> userman)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715
Task.Run(async () =>
{
try
{
bool roleexists = (await roleman.RoleExistsAsync("Admin"));
bool rolecreated = false;
if (!roleexists)
{
var newRole = new IdentityRole("Admin");
rolecreated= (await roleman.CreateAsync(newRole)).Succeeded;
}
if (roleexists||rolecreated)
{
var user = new ApplicationUser { UserName = "****", Email = "***" };
string userPWD = "****";
if((await userman.FindByEmailAsync(user.Email)) == null)
{ var res = await userman.CreateAsync(user, userPWD);
if (res.Succeeded)
{
var added = await userman.AddToRoleAsync(user, "Admin");
//await userman.UpdateAsync(user);
}
}
}
}
catch (Exception ex)
{
}
});
app.UseMvc(routes =>
{
routes.MapRoute(name: "area_route",
template: "{area:exists}/{controller}/{action}/{id?}",
defaults: new { action = "Index" });
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
from aspnetcore.identity.ravendb.
When the user is created, do you see a password hash assigned to the user object in the database?
For instance like that,
{
"UserName": "[email protected]",
"Email": "[email protected]",
"EmailConfirmed": false,
"PasswordHash": "AQAAAAEAACcQAAAAEI/tjQ2t/sy8jVDzwzFO06uWxv2SGin1J5rx+zfRauQ8dvoIUYl0Kulx/98nLKMsxg==",
"SecurityStamp": "581cc3e6-136d-42ec-9d1a-1b93c5fd4838",
"PhoneNumber": null,
"PhoneNumberConfirmed": false,
"TwoFactorEnabled": false,
"LockoutEnd": null,
"LockoutEnabled": true,
"AccessFailedCount": 0,
"Roles": [],
"Claims": [],
"Logins": []
}
I used the default MVC application created by Visual Studio and was able to self register and and login. Please try that and let me know if it worked.
from aspnetcore.identity.ravendb.
the user gets generated and auto logged in,
but after logging in, i cant login again.
further, it is possible to register twice,
could something be wrong with uniqueconstraints ?
how do i verify (and/or correct) ?
{
"UserName": "[email protected]",
"Email": "[email protected]",
"EmailConfirmed": false,
"PasswordHash": "AQAAAAEAACcQAAAAELT6/Oy0onQ1lfR6f5juNKMlBhrriSsYXU0UnPCwNvG3cOCNepfuYxxRTi5h4+Y+gg==",
"SecurityStamp": "be01a81c-30a4-49dd-9745-c7f1b4c9e3ea",
"PhoneNumber": null,
"PhoneNumberConfirmed": false,
"TwoFactorEnabled": false,
"LockoutEnd": null,
"LockoutEnabled": true,
"AccessFailedCount": 0,
"Roles": [],
"Claims": [],
"Logins": []
}
from aspnetcore.identity.ravendb.
it was the uniqueconstraintsbundle not being installed correctly.
thx for the support !
from aspnetcore.identity.ravendb.
Related Issues (19)
- Upgrade to v3.5
- Add a separate project for Database and Filesystem extensions
- Upgrade to Raven 4.0 HOT 7
- Upgrade to .NET Core 2.0 HOT 5
- Claims cannot be removed from role HOT 1
- Add sample project
- Add compatibility with NetStandard 1.3
- Tag all releases
- Upgrade to Raven 3.5.6
- ravendb client 4.2.0 compatibility HOT 2
- Add indexes where needed
- Explore GitHub actions for deployments
- Look into whether Claims and Roles should be stored in separate collections HOT 1
- 'IServiceCollection' does not contain a definition for 'AddRavenDbAsyncSession' and no extension method 'AddRavenDbAsyncSession' accepting a first argument of type 'IServiceCollection' could be found HOT 5
- Remove unnecessary registration of the UniqueConstraintsBundle from Configuration block of Startup.cs
- TypeLoadException: Inheritance security rules violated HOT 3
- Migrate to .csproj
- FindByEmailAsync is always null HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from aspnetcore.identity.ravendb.