C
C#5w ago
im_blind

Trouble implementing Identity

Hi so basically, I'm making a asp .net core web app and i want to use JWT and Identity (cause i heard google api for login, opts,.. are good) Thing is, the Database has already been constructed before hand and used scaffold to generate them in my .net project Therefore I already got a User entity. I watched some vids on yt guiding that I should extend the IdentityContext, IdentityUser, write stuff in program.cs files and how to use them in controllers. But these 2: IdentityContext, IdentityUser i've only extended, that's it One more problem is that, some recommended creating ApplicationUser? but I already have my User so is it needed? I then made my own login controller, and ran on swagger. It returned this { Invalid column name 'NormalizedUserName'. Invalid column name 'Id'. Invalid column name 'AccessFailedCount'. Invalid column name 'ConcurrencyStamp'. Invalid column name 'EmailConfirmed'. Invalid column name 'LockoutEnabled'. Invalid column name 'LockoutEnd'. Invalid column name 'NormalizedEmail'. Invalid column name 'NormalizedUserName'. Invalid column name 'PasswordHash'. Invalid column name 'PhoneNumberConfirmed'. Invalid column name 'SecurityStamp'. Invalid column name 'TwoFactorEnabled'. Invalid column name 'UserName'. } Now some told me that it's DB related and suggested I migrate add Identity and then update the Database but then I got errors from the tables constructed before Is Identity really needed for outside apis like google,....? If yes, how should i fix this? If no, what should I do instead?
70 Replies
Salman
Salman5w ago
Handling auth on your own is a complex thing and not recommended especially when you're the begineer. Identity is a good platform to handle authentication and authorization in your .Net Projects. You should delete your custom auth implementation and use the one that come with Identity . And yes as you know, if you wanna customize the user i.e wanna add additional properties you can simply extend the IdentityUser entity
Jimmacle
Jimmacle5w ago
those errors mean your EF model doesn't match your database structure
Salman
Salman5w ago
Also by using Identity , you'd get a lot of endpoints and pages for the auth ready made so you'd spend less time in managing auth related stuff in your application.
im_blind
im_blind5w ago
yes that would very much be more convenient I have tried to extended IdentityUser I think the problem would be about the database that has been constructed beforehand ? cause I am unable to update database after migrating
Jimmacle
Jimmacle5w ago
what do you mean by the database is constructed beforehand by migrations?
im_blind
im_blind5w ago
I don't really know whether I should just redesign the DB or find another method no no
Salman
Salman5w ago
if your database hasn't much data already , then you need to delete the previous migrations and add new ones or even delete the db
Jimmacle
Jimmacle5w ago
you should be using migrations
im_blind
im_blind5w ago
we were tasked with making the DB first thus creating seperately in the sql server then we scaffolded it into the .net project
Salman
Salman5w ago
also can you show the new User class that you're extending from the IdentityUser ?
Jimmacle
Jimmacle5w ago
identity and scaffolding are a really bad mix because identity tables are defined code-first
Jimmacle
Jimmacle5w ago
trying to copy it by hand is error prone and a poor use of time
im_blind
im_blind5w ago
it's a mess sr
Salman
Salman5w ago
that's wrong. You're also defining those properties that already exist in the Identity User table or model. Please remove them and specify only those that don't exist in the Identity's User model.
im_blind
im_blind5w ago
I see
Salman
Salman5w ago
c#
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;

namespace JewelryProduction.Core;

public partial class User : IdentityUser
{

public DateOnly? DateOfBirth { get; set; }

public virtual ICollection<CustomerRequest> CustomerRequests { get; set; } = new List<CustomerRequest>();

public virtual ICollection<Message> MessageCustomers { get; set; } = new List<Message>();

public virtual ICollection<Message> MessageSaleStaffs { get; set; } = new List<Message>();

public virtual ICollection<Order> OrderCustomers { get; set; } = new List<Order>();

public virtual ICollection<Order> OrderManagers { get; set; } = new List<Order>();

public virtual ICollection<Order> OrderProductionStaffs { get; set; } = new List<Order>();

public virtual ICollection<Order> OrderSaleStaffs { get; set; } = new List<Order>();

public virtual ICollection<_3ddesign> _3ddesigns { get; set; } = new List<_3ddesign>();
}
c#
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;

namespace JewelryProduction.Core;

public partial class User : IdentityUser
{

public DateOnly? DateOfBirth { get; set; }

public virtual ICollection<CustomerRequest> CustomerRequests { get; set; } = new List<CustomerRequest>();

public virtual ICollection<Message> MessageCustomers { get; set; } = new List<Message>();

public virtual ICollection<Message> MessageSaleStaffs { get; set; } = new List<Message>();

public virtual ICollection<Order> OrderCustomers { get; set; } = new List<Order>();

public virtual ICollection<Order> OrderManagers { get; set; } = new List<Order>();

public virtual ICollection<Order> OrderProductionStaffs { get; set; } = new List<Order>();

public virtual ICollection<Order> OrderSaleStaffs { get; set; } = new List<Order>();

public virtual ICollection<_3ddesign> _3ddesigns { get; set; } = new List<_3ddesign>();
}
here's the corrected model
im_blind
im_blind5w ago
but that wouldn't mess up the relations in DB right?
Salman
Salman5w ago
what relations also listen what the orders, customers and all that stuff need to do with the User entity ? You need to create separate entities for them and don't mix them up with the User.
Jimmacle
Jimmacle5w ago
those relationships look weird to begin with, why so many to the same type of entity also virtual is bad, that suggests lazy loading which you shouldn't use
im_blind
im_blind5w ago
they are other entities that are in relations with User. There are seperate entities, but arent these required if one is a Foreign key for another? These were basically auto generated based on the DB my teamates made. "virtual" and the ICollections included
Jimmacle
Jimmacle5w ago
i'm going to guess you have normalization issues in your database design for example you probably shouldn't have 4 different tables for orders, but a column to discriminate order types in a single table
Salman
Salman5w ago
something feels off with your database structuring can you describe your complete current database design ?
im_blind
im_blind5w ago
yes, lemme go get it
im_blind
im_blind5w ago
running the whole thing should create the DB smoothly
im_blind
im_blind5w ago
in SQL server
Jimmacle
Jimmacle5w ago
we're not asking about the literal sql really, more the reasoning behind why certain tables exist also i can't download files, use $paste if you can
MODiX
MODiX5w ago
If your code is too long, you can post to https://paste.mod.gg/ and copy the link into chat for others to see your shared code!
Salman
Salman5w ago
that's a lot to read but you could describe it in an easy and simple way i.e you could list the name of the entities, their purpose and the relations among them
im_blind
im_blind5w ago
alright, ill try my best cause there's a lot so the entities are: User, Role, CustomerRequest, Order, Message, 3DDesign, ProductSample, Collection, Gold, Gemstones, Category, PaymentMethod and Insurance This is a web app for JewelryProduction: make jewelry based on customer's demands Message: messaging between Users (customer, staff...) 3DDesign: the design of a product, required in Order, ProductSample and Request ProductSamples: product on display Gold: used to make product and provide price range. Needed in CustomerRequest and ProductSample Gemstone: diamonds,.... for production, needed in CustomerRequest and ProductSample Role is just an entity to categorize Users like customer, manager,... CustomerRequest: A description of the desired product/ A form for customers to provide desired properties for a product Order: Once the request is done, an order is then created. Collection for ProductSamples: basically like Category for Product Samples Category: category for Gemstones Insurance: Just documents for Orders Payment method: via Banking, implement sandbox it's ... complicated like order requires both User (customer) and User (staff)
Salman
Salman5w ago
1. Why 3DDesign is required in Order. It makes more sense in Customer Request like when customer would request a jewelry of certain design. 2.Instead of Product Samples I'd rather call it Products that would be displayed or used across the applications. 3.Collection entity doesn't make any sense to me here. Category is also a collection. 4.User, Roles and similar entities will be handled by the Identity mostly and you'd customize them according to your needs as discussed previously. 5. Payment Method can just be an enum instead of a class also for the relationships, you'd need to think very carefully . You don't wanna relate entities in a wrong way together. Think of them like each user can have many orders but each order can belong to a single user so it's a many to one relationship. Many Orders - > 1 User. So in this way try to relate all the entities together. Personally, while designing schemas and apps, I take help from the GPT as well to figure out the relations and stuff. It's not guaranteed to produce a perfect solution but can be helpful and gives you some pretty good ideas sometimes if asked correctly .
im_blind
im_blind5w ago
Thanks for the reply. 1. The flow is that the request is like a form that customers fill in, like the requirements. Then it is sent to the staffs to evaluate and provide quotation. Only after the quotation have been approved by both parties will the order be created. Now the 3ddesign is required in order as it has not been finalized, so the Design Staff might exchange suggestions with customers for modifications 2. It does make more sense, ill do that yes 3. Collection is like a collection of products related to each other. Like when there's a Summer 2024 Collection that has a necklace, bracelet, ring,... Whereas Category is used to categorized the gemstones only. This could be the Naming that might be confusing 4. I have noted this. So I should only provide properties that aren't in Identity. But we did a db first approach and we had to add necessary attributes to User. Does the part where u suggested I remove properties that exist in Identity model be used in Code only or both Code and DB? 5. I will take this in thanks If the Identity already has User and Role, then should I still include them in the db before i migrate?
Salman
Salman5w ago
Before Migration, the only thing you need to do is to configure the Identity and roles properly. Like registering the Identity in the Program.Cs, in the DB Context and Customizing the User as discussed before. Nothing else. You don't need to manually add something to the db . When you'll add the migration, Identity will create all the necessary auth tables for you. And it doesn't matter wether you created the database first or not in this case .
Salman
Salman5w ago
GitHub
GitHub - salmanhaider14/EcommerceWebApiDotNet
Contribute to salmanhaider14/EcommerceWebApiDotNet development by creating an account on GitHub.
Salman
Salman5w ago
Look at this API that I created, see how identity and roles are configured . Note that this is a web API, and identity config can vary slightly based on the project template you are using i.e blazor or MVC etc.
im_blind
im_blind4w ago
I think I understand it a bit now after seeing your project I think im gonna redesign my db and I understand where i went wrong in my project now
im_blind
im_blind4w ago
1 question look at the Order - User pls let's say the order needs involvement of the customer, sale staff, manager, production staff then my peers drew up to 4 relationship indicating those 4 relationships, this is still correct right?
No description
im_blind
im_blind4w ago
another one is this if i want a customized User table that uses AspNetUsers then i should make AspNetUser have a 1:1 relationship with Users right?
No description
Salman
Salman4w ago
I mean what kind of involvement all those roles would require in Order ? And how you want those roles to interact with Order in the application. Users and AspNetUsers are the same thing. You don't need to do that. You just extend the Identity user, add the additional fields and that's all .
im_blind
im_blind4w ago
Ah yes so like, customer can obviously track their order right? Then the sale staff can and manager should also be able to track it (manager is optional of course). And then the production staff should be able to update the status of the order for instance like whether the product is done with the body, done with the gemstone or whether it is done or stuff like that. ah so in db i should just scrap the User and use AspNetUsers directly. Whereas in the Code, I can do a User class which extends IdentityUser right? u might be asking why the sales staff is involved, we intend to make them like the jack of all trades. Involving with the process of a jewelry production process from start to finish. Basically like customer service
Salman
Salman4w ago
The simplest approach can be that you make multiple roles i.e Customer, Staff etc. And then set the authority i.e Customer can view their orders and track it. Staff Role can not only view the order but update the status as well . And yes for this simple approach you would need to add multiple Foreign Keys (FK) in the Orders table pointing towards each role.
im_blind
im_blind4w ago
I see, then I guess we correct on that part if i do this approach, then would the User identity as the AspNetCore in the db?
Salman
Salman4w ago
When you'll make a new user class that'd extend the existing IdentityUser, now this new class will be used in the code i.e In the DB Context and in the Program.cs etc. And to access the user and get the information. You would use the apis provided by the Identity . Are you making a Web Api ?
im_blind
im_blind4w ago
ah yes i am
Salman
Salman4w ago
what will be the frontend in ?
im_blind
im_blind4w ago
React
Salman
Salman4w ago
fine then make sure you Apis are consistent and well organized so that the frontend can consume it easily
im_blind
im_blind4w ago
I'll try yes At first, i didnt use Identity but only JWT in which we tested it on the FrontEnd side. It ran fine. It's just the Identity that confuses me
Salman
Salman4w ago
also IdentityApiEndpoints are not customizable, as you can see in my project I had to make my own register endpoint to add the roles support. Because by default the /register endpoint of Identity doesn't support adding roles. There's nothing confusing when you understand it .
im_blind
im_blind4w ago
only at first yeah, the tutorials on yts are kinda diverse with different methods and stuff so it was confusing
Salman
Salman4w ago
One separate approach can be that while registering the user on the frontend weather it's the customer or staff. You send the request to the api and the api will assign the role to the user. So instead of making another /register endpoint you can rather make a /assignRole endpoint that will take a user and role and will assign that role to the user .
Salman
Salman4w ago
Patrick God
YouTube
.NET 8 Authentication with Identity in a Web API with Bearer Tokens...
🚀 Join the .NET Web Academy: https://learn.dotnetwebacademy.com 💖 Support me on Patreon for exclusive source code access: https://patreon.com/_PatrickGod 🚀 Get the .NET 8 Web Dev Jump-Start Course for FREE: https://dotnet8.patrickgod.com 🐦 Let's get social on Twitter/X: https://twitter.com/_PatrickGod 🔗 Let's connect on LinkedIn: https://www.li...
Salman
Salman4w ago
It's a very good tutorial .
im_blind
im_blind4w ago
i havent seen this one yet, will do thanks i'll try to update once I finish modifying them
Salman
Salman4w ago
Salman
Salman4w ago
Official Guide for customizing Identiy User and other configurations and models .
im_blind
im_blind4w ago
oh sr, 1 more question
Salman
Salman4w ago
sure
im_blind
im_blind4w ago
public class Order { public Guid Id { get; set; } public required Guid UserId { get; set; } public required DateTime OrderDate { get; set; } public required OrderStatus OrderStatus { get; set; } public IdentityUser? User { get; set; } public required List<OrderItem> OrderItems { get; set; } } how did u make the relationship between User and Order? was it the line public IdentityUser? User { get; set; }? cause i didnt see the relationship in the AppContext either If I were to make a customized User class then i should also add it into both the order and the AppContext right?
No description
Salman
Salman4w ago
In the Orders table I'm adding a FK UserId which points to the User to whom the order belongs. And IdentityUser is the navigation property that EfCore will fulfill automatically for you . So this is a relation . And if you're making a new User then instead of IdentityUser you'll use the newly created user class. To be sure, you need to look into the official guide once . and in your newly created user class you'll add this property as well like :
c#
public List<Order> orders {get; set;}
c#
public List<Order> orders {get; set;}
im_blind
im_blind4w ago
i see, but wait does mean that the IdentityUser navigation property automatically recognizes the UserId as the fk?
Salman
Salman4w ago
I'll recommend you to must go through this official guide for relations once : https://learn.microsoft.com/en-us/ef/core/modeling/relationships
Introduction to relationships - EF Core
How to configure relationships between entity types when using Entity Framework Core
im_blind
im_blind4w ago
in your situation of course
Salman
Salman4w ago
yes , Identity automatically knows that User and UserId are related. You need to name your properties like that to left no room for confusion for Identity .
im_blind
im_blind4w ago
holy, that's neet
Salman
Salman4w ago
And to be more sure you can define your relationships manually in the DbContext class like I did but that's not required if your entities are well made .
im_blind
im_blind4w ago
i see i see
Salman
Salman4w ago
this is a must read blog
im_blind
im_blind4w ago
I'll go read it right away thanks a bunch
Salman
Salman4w ago
np
Want results from more Discord servers?
Add your server
More Posts