After that i renamed AspNetUsers to Utente, because i want that my application use always 'Utente' name.
After i created all classes :
public class AppDbContext : IdentityDbContext<User> { public AppDbContext() : base("DefaultConnection", throwIfV1Schema: false) { }
<div class="highlight highlight-html">
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<AppDbContext>(null);
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>().ToTable("Utente");
}
public static AppDbContext Create()
{
return new AppDbContext();
}
}
</div>
public class AppUserManager : UserManager<User> { public AppUserManager(IUserStore<User> store) : base(store) { }
<div class="highlight highlight-html">
public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
{
var manager = new AppUserManager(new UserStore<User>(context.Get<AppDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<User>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure ApplicationUser lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the ApplicationUser
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<User> {
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<User> {
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<User>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
</div>
public class AppSignInManager : SignInManager<User, string> { public AppSignInManager(AppUserManager userManager, IAuthenticationManager authenticationManager) : base(userManager, authenticationManager) { }
<div class="highlight highlight-html">
public override Task<ClaimsIdentity> CreateUserIdentityAsync(User user)
{
return user.GenerateUserIdentityAsync((AppUserManager)UserManager);
}
public static AppSignInManager Create(IdentityFactoryOptions<AppSignInManager> options, IOwinContext context)
{
return new AppSignInManager(context.GetUserManager<AppUserManager>(), context.Authentication);
}
}
</div>
in the App_Start, is created Startup class :
Public Sub ConfigureAuth(app As IAppBuilder)
<div class="highlight highlight-html">
app.CreatePerOwinContext(AddressOf AppDbContext.Create)
app.CreatePerOwinContext(Of AppUserManager)(AddressOf AppUserManager.Create)
app.CreatePerOwinContext(Of AppSignInManager)(AddressOf AppSignInManager.Create)
app.UseCookieAuthentication(New CookieAuthenticationOptions With {
.AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
.Provider = New CookieAuthenticationProvider With {
.OnValidateIdentity = SecurityStampValidator.OnValidateIdentity(Of AppUserManager, Sportrick.Model.User)(
validateInterval:=TimeSpan.FromMinutes(30),
regenerateIdentity:=Function(manager, user) user.GenerateUserIdentityAsync(manager))
}
})
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie)
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5))
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie)
End Sub
</div>
In the End, in accountController :
<HttpPost> <AllowAnonymous> Public Async Function LogOn(ByVal model As LogOnViewModel, ByVal returnUrl As String) As Task(Of ActionResult) If Not ModelState.IsValid Then Return View(model) End If
<div class="highlight highlight-html">
Dim result = Await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout:=False)
Select Case result
Case SignInStatus.Success
Return RedirectToLocal(returnUrl)
Case SignInStatus.LockedOut
Return View("Lockout")
Case SignInStatus.RequiresVerification
Return RedirectToAction("SendCode", New With {Key .ReturnUrl = returnUrl, Key .RememberMe = model.RememberMe})
Case Else
ModelState.AddModelError("", "Invalid login attempt.")
Return View(model)
End Select
End Function
</div>
Error Login :
The foreign key component 'UserId' is not a declared property on type 'Login'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.
UserId is the Key of User entity (i have mapping in EDMX model tra Entity User <-> Table Utente)
Do you want to add Identity to your existing project?
If this is the case, you can view a detailed tutorial at this link.
Best Regards,
YihuiSun
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
None
0 Points
1 Post
Asp.net Identity to an Existing Database
Feb 03, 2021 09:59 AM|eljallouly@gmail.com|LINK
Hello,
I have one aplication that use custom authentication, yet i need to implement asp.net Identity, i have some problems to do this.
My user table : Utente (IDUtente, Username, .......)
i Deleted Utente table and i add all columns to AspNetUsers, the new table AspNetUsers has columns :
<div class="highlight highlight-html"> </div>After that i renamed AspNetUsers to Utente, because i want that my application use always 'Utente' name.
After i created all classes :
public class AppDbContext : IdentityDbContext<User> { public AppDbContext() : base("DefaultConnection", throwIfV1Schema: false) { }
<div class="highlight highlight-html"> </div>public class AppUserManager : UserManager<User> { public AppUserManager(IUserStore<User> store) : base(store) { }
<div class="highlight highlight-html"> </div>public class AppSignInManager : SignInManager<User, string> { public AppSignInManager(AppUserManager userManager, IAuthenticationManager authenticationManager) : base(userManager, authenticationManager) { }
<div class="highlight highlight-html"> </div>in the App_Start, is created Startup class :
Public Sub ConfigureAuth(app As IAppBuilder)
<div class="highlight highlight-html"> </div>In the End, in accountController :
<HttpPost> <AllowAnonymous> Public Async Function LogOn(ByVal model As LogOnViewModel, ByVal returnUrl As String) As Task(Of ActionResult) If Not ModelState.IsValid Then Return View(model) End If
<div class="highlight highlight-html"> </div>Error Login :
The foreign key component 'UserId' is not a declared property on type 'Login'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.
UserId is the Key of User entity (i have mapping in EDMX model tra Entity User <-> Table Utente)
Contributor
2760 Points
787 Posts
Re: Asp.net Identity to an Existing Database
Feb 04, 2021 07:53 AM|YihuiSun|LINK
Hi eljallouly,
I can't see UserId in the code you provided.
Do you want to add Identity to your existing project?
If this is the case, you can view a detailed tutorial at this link.
Best Regards,
YihuiSun