extending aspnet identity to include additional properties for WEB FORMS - c#

i am currently implementing aspnet identity(code first) for WEB FORMS(VS 2013) i would like to know how to add additional properties like date of birth to the entity.
i can currently do this via MVC but have issues on aspnet WEBFORMS.

You should create a class which inherits from IdentityUser and add your custom properties to it. An example would look like the following
public class ApplicationUser : IdentityUser
{
public DateTime DateOfBirth { get; set; }
}
The next step would be to change your database context to use this new user
public ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
...
}
If that doesn't solve your problem you should post what your issues actually are.

Related

Specifying correct context to add Identity into existing database

Similar questions have been posted before (1, 2, 3), but the situation is different.
I have an .Net Core 7 app using EFCore with some existing entities. Now that everything in there is tested and working, I'd like to add the Identity functionality and then link AspNetUsers to a couple of my existing entities.
Currently there are no identity tables, nor any sort of tables used by the Identity functionality.
Using the Microsoft tutorial Scaffold Identity into a Razor project without existing authorization I get to the step whereby I need to specify my database and user contexts.
After unsuccessfully looking for documentation I entered the database context as being the one which is used in my data project ('EventFinderData' below - a different project to my web app, but within the same solution). I then created a new user context...
After the scaffolding is complete, I get a number of ambiguous reference errors as the scaffolding process creates a new data context:
// This is a duplicate class of that within the EventFinderData project, which is already referenced within my web app
public class EventFinderContext : IdentityDbContext<EventFinderWebAppRazorUser>
{
public EventFinderContext(DbContextOptions<EventFinderContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
I tried to make both classes partial, but then when I add a migration I get:
More than one DbContext was found. Specify which one to use. Use the
'-Context' parameter for PowerShell commands and the '--context'
parameter for dotnet commands.
Some experts seem to recommend starting a new project with Identity included already, and building out from there, but its going to be a big job.
What do I need to modify please in order for this scaffolding process to bolt into my existing EFCore logic?
Alternatively is Identity supposed to use a dedicated (separate) context? That would seem unintuitive given the tables need relationships between identity entities and my existing entities.
Update
Based on suggestions, here are the three classes I get after adding the Identity functionality:
Data project (containing Entities and migrations):
EventFinderContext.cs
namespace EventFinderData
{
public class EventFinderContext : DbContext
{
public DbSet<EventItem> EventItems { get; set; }
public DbSet<EventCategory> EventCategories { get; set; }
public EventFinderContext(DbContextOptions<EventFinderContext> options) : base(options)
{
}
}
}
Web app project - Classes created by VS/Identity
Areas\Identity\Data\EventFinderWebAppRazorContext.cs
namespace EventFinderWebAppRazor.Data;
public class EventFinderWebAppRazorContext : IdentityDbContext<EventFinderWebAppRazorUser>
{
public EventFinderWebAppRazorContext(DbContextOptions<EventFinderWebAppRazorContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
Areas\Identity\Data\EventFinderWebAppRazorUser.cs
namespace EventFinderWebAppRazor.Areas.Identity.Data;
public class EventFinderWebAppRazorUser : IdentityUser
{
}
Program.cs
builder.Services.AddDbContextFactory<EventFinderContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("EventFinderConnString"),
ss => ss.UseNetTopologySuite())
.EnableSensitiveDataLogging());
builder.Services.AddDefaultIdentity<EventFinderWebAppRazorUser>(
options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<EventFinderWebAppRazorContext>();
Not sure if something changed (.net6 here) but to add the dot net identity framework to your existing context all you have to do is just provide that context when adding it to the IServiceCollection.
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
})
.AddEntityFrameworkStores<ApplicationDbContext>()
You will need to change your DbContext so it inherits from
IdentityDbContext<ApplicationUser>
This will only provide the required services, not the different views and UX flows that comes when you scaffold it. So no login/logout, password resets, MFA setup etc...
I hope this will help.
Update
Based on the OP's update, the following updates are required.
Areas\Identity\Data\EventFinderWebAppRazorUser.cs
Move this class to your Data project. It will become a part of your own entity model. Make sure that the namespace is also updated. Although this is not really necessary, but it is nice to have all entities in the same namespace.
Areas\Identity\Data\EventFinderWebAppRazorContext.cs
Delete this file/class. This is the extra context created by the scaffolding process, but as we want to use our own context we don't need it.
EventFinderContext.cs
Update this class like below.
namespace EventFinderData
{
public class EventFinderContext : IdentityDbContext<EventFinderWebAppRazorUser>
{
public DbSet<EventItem> EventItems { get; set; }
public DbSet<EventCategory> EventCategories { get; set; }
public EventFinderContext(DbContextOptions<EventFinderContext> options) : base(options)
{
}
}
}
Program.cs
Update this file like below. And make sure all types resolve by updating the usings.
builder.Services.AddDbContextFactory<EventFinderContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("EventFinderConnString"),
ss => ss.UseNetTopologySuite())
.EnableSensitiveDataLogging());
builder.Services.AddDefaultIdentity<EventFinderWebAppRazorUser>(
options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<EventFinderData.EventFinderContext>();

MVC Identity and Model classes

I'm trying to realize a MVC .NET core application with Identity scaffolded.
I stared from an empty MVC app, I added some Identity scaffolded items, with a specific IdentityDbContext and a specific IdentityUser:
public class MyCustomUser : IdentityUser
{
[PersonalData]
[Column(TypeName = "nvarchar(100)")]
public string FirstName { get; set; }
}
Then I created some custom model classes in the Models folder and I would like to force the EF to include those classes in the migration evoked with
Enable-Migrations
Add-Migration "MyMigration"
Update-Database
As a result I expect to see on my DB all the tables for the authentication (AspNetRoles, AspNetUsers (with its new column "FirstName") etc) and the tables created using the classes in \Models.
How can I achieve this?
Would you suggest another way to handle identity and models using EF?

AbpDbContext and IdentityDbContext

I have an ASP.NET Core (v. 2.2) application that uses IdentityDbContext<User, Role, string>.
I'm adding Abp Framework to the application, I want to use AbpDbContext.
How to combine the functionality of two contexts?
You need to create a module class like below
public class BlogModule : AbpModule
{
}
and add your other module dependency in the attribute. Something like this
[DependsOn(typeof(BlogModule))]
public class WebAppModule : AbpModule
{
}
And read https://docs.abp.io/en/abp/latest/Module-Development-Basics

Asp.Net MVC Identity and Our Database single context for whole application

I have used MVC Identity for user login and registration purposes....but i needed to add additional database table also like this are completly unrelated with Identity database table...in my application i use code first.....i have made class for this.....but i want a single context in whole application
public DbSet<Dept> Dept{ get; set; }
public DbSet<Course> Course{ get; set; }
public DbSet<Etc> Etc{ get; set; }
As asp.net identity have ApplicationDBContext and i was using other database context which is defined by this
public class MainContext : DbContext
So what i want is i should be able to create my database table and Identity table when database changes detected and i am creating user and role when application starts at ApplicationDbInitializer which is working ok.
Now i want just a single context for whole application....
Things i have tried or think is inherit Maincontext with ApplicationDbContext
But still i can see 2 context and Other thing is i can inherit from IdentityDbContext but still there will be 2 context.
Show me simple example if possible.
Thanks.

Implementing rights with ASP.NET Identity

We are currently working on a smaller ASP.NET MVC 5 application using ASP.NET Identity. It allows us to maintain different projects and their tasks. We recently implemented basic authentication so we are able to register a user with our site and login with them.
We want to be able to manage access rights on project basis so we can say for every single user that he has read, write, admin or no permissions for a specified project.
My first thought was that we can create a simple new table in our database which stores the user rights. But I feel that there might be a built-in way to achieve this with ASP.NET Identity.
So my question really is, which path we should follow - manually building a new table to administer the rights or use something built-in provided by ASP.NET Identity.
use something built-in provided by ASP.NET Identity
The only things you could use there are claims or roles and both are not built for what you want IMO.
So I would go with your own table which links the project to a user, e.g.:
public class UserProjectRights
{
[Key]
public ApplicationUser User { get; set; }
[Key]
public Project Project { get; set; }
public AccessRight Right { get; set; }
}
Then whenever you do some actions where a specific right is required you need to check for that. There are several ways how you could do that. In my app I created "access right check extensions" like the following (I have defined a common interface for all "access right entities" to "reuse" that method):
public static bool? CanView(this ApplicationUser user, Project project)
{
var userRight = project.Rights.FirstOrDefault(r => r.User == user);
return userRight == null ? (bool?)null : userRight.Right.HasFlag(AccessRight.View);
}
assuming AccessRight is an enum like:
[Flags]
public enum AccessRight
{
View,
Edit,
Admin
}
Then you can do something like the following in your logic:
if (user.CanView(project) == true)
{
// show project
}
I used bool? so I can implement different "default behaviour" as I know if null is returned there is no right defined.

Categories