Authentication made easy with ASP.NET Core Identity in .NET 8
Вставка
- Опубліковано 30 чер 2024
- Get the source code for this video for FREE → the-dotnet-weekly.ck.page/asp...
☄️ Master the Modular Monolith Architecture: bit.ly/3SXlzSt
📌 Accelerate your Clean Architecture skills: bit.ly/3PupkOJ
🚀 Support me on Patreon to access the source code: / milanjovanovic
ASP.NET Core Identity is the simplest approach to implementing authentication in .NET. With a few simple configuration steps, you can have cookie and token authentication up and running in minutes. Identity can also integrate with EF Core, allowing you to customize the database. In this video, I'll show you how to get started with ASP.NET Core Identity. We'll also explore the brand-new Identity endpoints.
Master Claims Transformation for Flexible ASP.NET Core Authorization
www.milanjovanovic.tech/blog/...
Join my weekly .NET newsletter:
www.milanjovanovic.tech
Read my Blog here:
www.milanjovanovic.tech/blog
Subscribe for more:
/ @milanjovanovictech
Chapters
0:00 Configuring Authorization and Authentication
0:49 Adding ASP.NET Core Identity
4:27 Customizing the IdentityDbContext
6:27 Testing the .NET 8 Identity endpoints
8:05 Implementing token authentication
8:55 Adding Authentication to endpoints - Наука та технологія
Get the source code for this video for FREE → the-dotnet-weekly.ck.page/aspnetcore-identity
Thank you so much for your videos. Im from Brasil and it really helps me, but I would like to see that approach with a database first. Is there a script to create the tables in the database, so I can map them in the code?
Milan's videos' value per second is always so high, lol. Absolutely no fluff whatsoever.
Value per second, now that's a nice metric
love it! clear and simple! thanks!
Thanks! :)
Great video! One thing was missed when discussing adding JWT tokens. If you are going to add both Application Cookies and Jwt Bearers, things are going to get wonky. Using the provided solution, you have to manually specify which scheme you want to use for every request. This code didn't work in Postman using JWT for example and would return a 404.
The solution is to change the Authorization setup to the following:
builder.Services.AddAuthorization(options =>
{
var policy = new AuthorizationPolicyBuilder(IdentityConstants.ApplicationScheme, IdentityConstants.BearerScheme)
.RequireAuthenticatedUser()
.Build();
options.DefaultPolicy = policy;
});
This means anything tagged with [Authorize] will allow both schemes automatically.
You can also decorate your class or method with Authorize attribute with Policy name. The framework will use the specified policy for that particular request. This allows using multiple schemes within application.
Awesome, thanks for adding this!
They are opaque bearer tokens, not JWT.
Thx!!! I did everything by the video and /me details part did not work. You saved me time for checking the stackoverflow on the solution for 2 schemas problem...and Milan recently started to give us non working solutions :) I enjoy doing some things on my own but sometimes it gets really wonky as you said :)
Very good! Thanks for sharing.
Most welcome!
wow. this makes things easier. i use to make the endpoints manually.
Nice
Thank you milan!
You bet!
AAAAAAAAAAAAAAAAA thanks thanks. I've been waiting for this video
What would you like to see next?
@@MilanJovanovicTech Microservices)
I know that identity is simple enough here but it could be really good to have a video on using oidc external authentication providers and how to configure oidc in dotnet backends together with a frontend application using maybe the bff pattern?😊
I may cover Keycloak soon :)
nice content, thanks
You're welcome
Thanks ❤
You're welcome 😊
Hello Milan can we add other models to this identity dbcontext? and when we run migration will it change them as well or just users
Yes, but I typically like to keep separate contexts and schemas for Identity and my domain models
Great, thanks! But can we use JWT here? or just Bearer?
Bearer, it's not a proper JWT. That would have to be implemented separately.
Very cool video but i just have a doubt. I see you extended IdentityUser and added Initials to the user table, but at the same time it didn't reflect on your register endpoint. Is it just a swagger thing meaning you could pass Initials in the payload?
No, Identity endpoints doesn't pick up the change
@@MilanJovanovicTech So what’s the point of using that endpoint if you cannot custom the json body?
@@Davide-zx7ig that's excactly what I am trying to figure out. I have extended the IdentityUser adding custom properties, but I can't send the custom properties to the /register endpoint. It is simply ignored.
@@LucaAzalim I had a project that I used Identity. One thing I did and it worked really well was extending IdentityUser and adding my custom properties. At the same time, I had to define my custom controller contract objects. In my service class I just used the UserManager class to perform all user related actions such as saving, changing password, etc
Hey I wonder how we use TwoFactorAuthentication in identity with using google or microsoft authenticator app can you make a video for this topic?
Great idea for a future video
System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).
?
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
})
.AddCookie(IdentityConstants.ApplicationScheme)
I Notice that Custom Property you Added [Initial] doesn't apply value or any custom property like [FirstName, LastName, ...] , is that normal?
and thank you for your great video
It's not included automatically on the register endpoint
we need more videos like this which covers full end to end steps
Coming up!
I wonder how can I add this to my project which follows clean architecture and DDD. I has a thought that I can put the ApplicationUser and related terms inside Infrastructure/Identity, include a foreign key from ApplicationUser to my domain user (customer and staff), change the DbContext to IdentityDbContext, add loginservice in Application layer. Is this okay?
Yes, that's an option
Why only run migrations on development? How do you apply them in other environments?
Manually, and preferably with SQL scripts.
In some projects, I'll use a tool to automate this. One example is RoundhousE
Which layer would the IdentyUser exist in a Clean Architecture solution? And how would it affect other layers?
Depends, do you want to use the AspNetCoreUsers table only, or also have your own?
how can I add custom claims on register, is it possible? I wanted to be able to add custom Role authorization in the apis but I haven't found a way so far... Also, disabling the register endpoint would be useful for sure
Is not possible.
@@10Totti thanks, at least I'm no longer going to spend time finding how to do it
@@rodrigo-5967 you can implement your own register endpoint instead of relying on MapIdentityEndpoints
Should be possible through the Claims table in the database. I'd refer to the docs for that part.
This makes met not take for granted how painless msal and entra has become when solving authentication/authorization. Especially when also integrating downstream apis. But then again, not everyone has vendor lock-in to azure.
Auth is such a complex topic. I'm glad we have good abstractions in place.
Why am i getting an error when I want to take the user info
System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).
Specify the scheme in AddAuthentication
We want you to explain the Bogus library and an explanation of its use with unit testing using Mock
👀👀 millan
Ok, sounds interesting
What do I need to adjust to use int as a key for all the generated classes
I believe it's IdentityUser, but check the docs for the exact syntax
Can I integrate web api with external authentication service like google or facebook with this library, without blazor identity side or mvc ?
Yes
Quick Question, I have been working on this for awhile now and I just can't get it to work. We have a SSO using Apereo CAS. Our Admin requires that our web apps make a call to the CAS server and use its login page and then it sends back a ticket for validation. I just can't figure out how to make the call using httpclient so that their page comes up and then get the data back. Have you ever done a video on something like that? I know other SSO like Google or MS are fairly easy because those are built in but I can't seem to get a third party one to work. Any ideas?
Shouldn't this be done from the client side?
@@MilanJovanovicTech There is no client side, this is a pure server side Blazor app.
@@MilanJovanovicTech Sorry what do you mean from the client side?
hello , I have an error when I'm trying to use a custom User:IdentityUser. The error is "Identity.BearerAndApplication was not authenticated. Failure message: Unprotected token failed".
If I use DbContext with simply IdentityDbContext all work.
Please can you help?
Not really
For example I don't want to allow users to register, is there a way to hide/remove this endpoint?
Not out of the box
I'd love to see this working with an external account like Google
Ok, that's a great idea for another video
Is it possible to configure the generated token or its expires time?
Yes, it's. as you're adding the Bearer token to service collection, you can pass the configuration after the schema.
Yes
Is there a way to disable register endpoint?
No. You cant override. But You can redirect it to another page.
Middleware.
It seems no, which is tragic
In clean architecture landscape, where the User class should be placed
Domain
@@MilanJovanovicTech torally agree but as its class we cannot use inside the domain as its referring an interface from identity package, in this way the domain need to reference infrastructure layer. So should it be good idea to use an IUser interface in domain and implementation on infrastructure layer?
Could you explain why we need IdentityServer4 ?
When did I say we needed it?
Nice tutorial thanks. Too bad it's very limited if we want to do customizations.
Yeah, that’s the worst part of it. It feels limited to POCs and demos
True, using these out of box authentication in real life can be a challenge if you want to customize anything.
It's not much different than integrating with an external IDP
can i authenticate using username instead of email?
I think so, though I'm unsure (from memory) what needs to change in the setup
An idea for a video, series of videos, course whatever (I could also be blabbering nonsense, because I'm not even sure it's possible.). Functional (Can be simple but not nonsense only suitable for a demo.) .Net API that can be AOT compiled. Maybe it's too early for that.
Ok, sounds interesting 👌
Can you please milan make a video about chain of responsability pattern
Already covered it many times - with MediatR pipeline behaviors
Is it necessary to do all this if I am going to use something like OKTA/EntraID?
Nope, you can just configure JWT for example
Any idea why i am getting the IEmailSender error?
Didn't register it with DI?
Thanks for this video I implemented same earlier but I faced a challange that when I am creating custom user class like as you added with initials I added firstname lastname string properties but I was unable to add those in registration because they were not reflecting so I had to make changes and made custom methods which overrides current identify flow
is not possible.
Sadly, you'll have to manage that on your own :/
Cookie vs jwt with?
I usually work with JWT
@@MilanJovanovicTech cool, do you have videos about refreshing tokens using jwts?
in my code give this error initials column
Did you run the migration?
What if I wanted to configure all of it inside of Infrastructure project (is it even a correct approach)? AddApiEndpoints method is missing, it comes from Microsoft.AspNetCore.Identity assembly.
Another concern is, what to do with custom User entity, it surely cannot be declared within Domain as it needs dependency on Identity... Should it belong to Infrastructure? There are a few unknowns.
PS. It would be lovely to have some more in depth video about this new .NET 8 authentication approach. Or perhaps could you include it into your Clean Architecture course? Thank you in advance!
I will try to cover these questions in a future video
@@MilanJovanovicTech Thank you! Forgot to add that I really appreciate your videos!
But extending custom class not possible! probably .net 9 will fix that!
Any issues about that you're tracking, perhaps?
Nice but unfortunately you tight everything to EF and a database :(
Can you explain a more simple way, when database , and especially EF is not wanted,
because , you know, EF is not law ;)
Why not use an external IDP then?
@@MilanJovanovicTech why not. Which one do you recommend?