✅ Can't Authenticate User

I am working on a small WebApp and I have 3 user types. In my EF DB Migration I defined the following tables: Logins, Users and another table called Roles. In the Logins table I hold an Id which is the same to the UserId, the email, hashed password and the password salt. In the Users table I hold all of the user data such as the name and a FK for the role. In the roles table I have an Id and RoleType string. Currently I have the "Standard" role and the "Administrator" role. I have an overview page for users that are not logged in that should not be visible to authenticated users. And the pages that are accessed by authenticated users are not visible for non-authenticated users. Meanwhile for the administrators I will provide the same pages but I may add more buttons, so the access should be similar (I assume). I have tried adding a cookie manually with the session, but I don't know how to authorize it. Next I tried adding custom policies, but that didn't work and I wasn't able to access any page. And now I tried adding Identity, but it seems like my Users and Roles tables/models are conflicting with the ones provided by Identity. What should I do? Here's how a user logs in into my application:
52 Replies
Bunta Fujiwara (文太)
[HttpPost]
public IActionResult Login(LoginPoco loginPoco)
{
if (ModelState.IsValid)
{
var existingUser = _context.Logins.SingleOrDefault(u => u.Email == loginPoco.Email);

if (existingUser != null)
{
if (PasswordHasher.VerifyPassword(loginPoco.Password, existingUser.Password, existingUser.Salt))
{
HttpContext.Session.SetString("UserId", existingUser.Id.ToString());

return RedirectToAction("Index", "Home");
}
}

ModelState.AddModelError(string.Empty, "Wrong email or password.");
return BadRequest(new { success = false, message = "Wrong email or password." });
}

var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
return BadRequest(new { success = false, message = "Validation failed", errors });
}
[HttpPost]
public IActionResult Login(LoginPoco loginPoco)
{
if (ModelState.IsValid)
{
var existingUser = _context.Logins.SingleOrDefault(u => u.Email == loginPoco.Email);

if (existingUser != null)
{
if (PasswordHasher.VerifyPassword(loginPoco.Password, existingUser.Password, existingUser.Salt))
{
HttpContext.Session.SetString("UserId", existingUser.Id.ToString());

return RedirectToAction("Index", "Home");
}
}

ModelState.AddModelError(string.Empty, "Wrong email or password.");
return BadRequest(new { success = false, message = "Wrong email or password." });
}

var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
return BadRequest(new { success = false, message = "Validation failed", errors });
}
Angius
Angius9mo ago
You would have to authorize it yourself Write authorization middleware, figure out a way how to hook it up to your controllers Alternatively... strip away your custom auth code and just use Identity
Bunta Fujiwara (文太)
How would you rate the difficulty of this?
Angius
Angius9mo ago
Hard to tell, to be honest. I never even tried doing that since Identity fits my needs
Bunta Fujiwara (文太)
Regarding the Identity part. Should I also rename my User and Role models? Or how would my DB architecture change?
Angius
Angius9mo ago
You would use Identity's users and roles That you can customize, of course But, yes, your database structure would change, Identity would introduce some tables and columns of its own It's a complete solution, with password reminders, 2FA, and so on
Bunta Fujiwara (文太)
Oh, I see. Well, I implemented the password hashing and salting on my own, I hope I won't have to get rid of that
Angius
Angius9mo ago
Identity uses SHA256 for password hashing, and it does the salting as well You can substitute it for your own, though. I replaced SHA256 with Argon2id
Bunta Fujiwara (文太)
I checked the documentation and it seems like I will still be able to define my user as long as it's named ApplicationUser. I am wondering if the User created by Identity will be replaced by my ApplicationUser or not and how I would be able to link the custom user to the roles
Angius
Angius9mo ago
No, you will be able to define your own user as long as it inherits from ApplicationUser It will have all the properties of ApplicationUser plus properties you yourself define
Bunta Fujiwara (文太)
I'll try using Identity then. Thanks!
Kringe
Kringe9mo ago
for simple custom authorization I return a jwt token from the login endpoint and use the authorize attribute on my controllers Idk what you use for frontend but with blazor you can also use the authorize attribute
Bunta Fujiwara (文太)
I have a classing MVC WebApp automatically generated I'm not sure if it usez Blazor. All I know is that it supports Razor syntax But wasn't JWT mostly for APIs? I guess I'll have to use attribute routing
Kringe
Kringe9mo ago
a okay i have not worked with that but isnt the screenshot you send an api?
Bunta Fujiwara (文太)
I guess it technically is since it's an api endpoint for a login that gets called from the views. But it just doesn't look like the APIs that are completely separate and use swagger
Angius
Angius9mo ago
Oh, cool thing about Identity: it scaffolds the login, registration, etc. pages for you Customizable, of course, but still
Bunta Fujiwara (文太)
Yeah, but weren't the scaffolded logins and registrations MVVM? (or Identity as a whole) I found this on StackOverflow
If you webapi and user interface are hosted in the same web application, token bases security does not buy you anything over the cookie based authentication provided by the built in authentication. That's because the authentication cookie gets sent back to the keep application on every HTTP request. When you make calls to a website other than the one you signed in on those cookies do not get sent. So JSON Web Tokens (JWT) provide a standard format for browser to send identity information to a website when a cookie isn't an option.
If you webapi and user interface are hosted in the same web application, token bases security does not buy you anything over the cookie based authentication provided by the built in authentication. That's because the authentication cookie gets sent back to the keep application on every HTTP request. When you make calls to a website other than the one you signed in on those cookies do not get sent. So JSON Web Tokens (JWT) provide a standard format for browser to send identity information to a website when a cookie isn't an option.
Angius
Angius9mo ago
What gets scaffolded are Razor Pages You can have it scaffold API endpoints as well, but they're not customizable yet Also, you said you're using MVC, so why would you use an API for auth?
Bunta Fujiwara (文太)
Isn't MVC just a coupled API and WebApp? Since in a way the controllers are just API endpoints that return HTML
Angius
Angius9mo ago
Eh, I guess An API usually means you receive and return JSON If you receive form data or just requests without data, we usually call it server-side rendering, or SSR
Bunta Fujiwara (文太)
I see. So I should go for Identity But would there be a way to get rid of the PasswordHash and Email and other redundant fields from the Identity User? I have a separate table for storing the user's email and password + salt and I don't think that it's proper to store that data in the User table
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Bunta Fujiwara (文太)
Well, I didn't even have an Authentication stack in place
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Bunta Fujiwara (文太)
Yeah, that's what I was trying to accomplish. I am just unsure on what to use. I want to rewrite as little as possible I did a DB migration with Identity since I received suggestions to use Identity. But now I realized that I have lots of redundant fields in my Users table
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
ophura
ophura9mo ago
:catgasm:
Bunta Fujiwara (文太)
In my previous architecture I had all of the login data such as the user email and hashed password and salt in a Logins table, with all the remaining user data in a Users table Just a personal project
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Bunta Fujiwara (文太)
A MVC app
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Bunta Fujiwara (文太)
The theme of the app is that it's a library, like an online library of books
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Bunta Fujiwara (文太)
I did MVC before in Rails
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Bunta Fujiwara (文太)
Yes, I am using .NET8
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Bunta Fujiwara (文太)
I didn't know that
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Bunta Fujiwara (文太)
I was wondering why I no longer had to write AJAX for my requets. Maybe that's the answer
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Bunta Fujiwara (文太)
I already have the UI part. I would prefer to avoid scaffolding a new UI, if possible. This way I would only lose half of my work instead of all of my work.
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Bunta Fujiwara (文太)
Can't I scaffold into my actual project and check against the previous commits in git? Or would that come with the risk of breaking stuff?
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Bunta Fujiwara (文太)
I created a project called Prototype since I'm kind of prototyping the authentication and authorization. Regarding the DB. I guess I'll have to get a new local DB going since my current one is on Azure with the free tier
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Bunta Fujiwara (文太)
I'll start following the guide since it's the learn section so there probably wont' be any issues Should I close the thread or leave it open in case of possible problems that may arise
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Bunta Fujiwara (文太)
Thank you all for the help!
Want results from more Discord servers?
Add your server