Get the source code for this video for FREE → the-dotnet-weekly.ck.page/aspnetcore-identity Want to master Clean Architecture? Go here: bit.ly/3PupkOJ Want to unlock Modular Monoliths? Go here: bit.ly/3SXlzSt
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?
It's explained really nicely, I like that you don't waste time and get straight to the point. Completely different from the official Microsoft documentation and tutorials, which rely on already generated code or don't have an easy to navigate structure. Thank you!
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.
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 :)
Thanks Jonah for this, now I want my all endpoints to be authorized by default so I used " .RequireAuthenticatedUser()" but that caused an issue for me where even the identity endpoints are throwing 401, what is the solution for that issue?
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?😊
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).
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.
Would love to see this video but greatly expanded for the developer who is still trying to get a handle on the Identity library. Otherwise can you recommend resources to get up to speed, so I could recreate this without being a monkey on the keyboard? Thanks greatly.
First of all great video, Small question say you have another service which you need authorization for how would you use your current service to authenticate it?
Hi, thank you for the video. I don't know why they don't add some extra endpoints for managing roles associated with User when registering. What the tips in that case ? Implementing a custom endpoint in order to associate role with a user ?
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).
@@MilanJovanovicTech Tanks for help, but I have one more question. How I can extend the "register" endPoint for my User Class? public class User : IdentityUser { public string? UserSurname { get; set; } public string? Address { get; set; } public DateTime DateOfCreation { get; set; } }
Thank you for video, i want to use it in clean architecture. But i have a question: where should i put creating, updating, deleting users and their roles?
What confuses me, if we are not implementing the registration process but just using the default how would you then use the provided /confirmEmail endpoint, in which step and where should i use 'sendgrid' for example to send a confirmation token to my user. ?
Thanks for the clear explanation video. But why use Docker? have to install Docker to run the app? it also seems that if you add Docker when creating the WebAPI app it will yield a nearly blank program.cs file.
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?
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
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?
@@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
@@MilanJovanovicTech well that is, AddIdentityCore options=> options.token.PasswordResetTokenProvider = TokenOptions.DefaultPhoneProvider Doing this has given me a 6 digit numeric code when calling usermamager.GeneratePasswordResetTokenAsync But for some reason when i call the identity's forgot password endpoint it emails a 8 digit alpha numeric code If i can somehow set the token provider to ToTpSecurityBasedTokenProvider that might help, but i cannot figure out how to do it yet
@@MilanJovanovicTechmoreover, i want to customize the content of the emails it is sending for registration or password reset etc, e.g put my required html , company details etc
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?
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?
@@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?
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
@@MilanJovanovicTech also it has other problems. It cannot be decoded like a jwt to see user claims. So i wrote custom login endpoint to get jwt token with claims
@@MilanJovanovicTech Thanks for the response, but I cannot generate a token with u UserMsnager. For that I need an extra package..At least according to all information I found in the internet...
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.
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!
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
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 ;)
Get the source code for this video for FREE → the-dotnet-weekly.ck.page/aspnetcore-identity
Want to master Clean Architecture? Go here: bit.ly/3PupkOJ
Want to unlock Modular Monoliths? Go here: bit.ly/3SXlzSt
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?
Fast, accurate, and understandable.
This is a fantastic tutorial video. You are truly a gem among TH-cam tutorial creators.
Glad it was helpful!
Yes, well said!
Absolutely. Really very well explained.
Milan's videos' value per second is always so high, lol. Absolutely no fluff whatsoever.
Value per second, now that's a nice metric
No BS, no yapping and straight to the point. This is my favourite video on .net identity.
Much appreciated 😁
It's explained really nicely, I like that you don't waste time and get straight to the point. Completely different from the official Microsoft documentation and tutorials, which rely on already generated code or don't have an easy to navigate structure. Thank you!
Most welcome!
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 :)
Thanks Jonah for this, now I want my all endpoints to be authorized by default so I used " .RequireAuthenticatedUser()" but that caused an issue for me where even the identity endpoints are throwing 401, what is the solution for that issue?
wow. this makes things easier. i use to make the endpoints manually.
Nice
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 as always. You are my fovrite youtuber
Thanks a lot! :)
we need more videos like this which covers full end to end steps
Coming up!
This is Awesome and more helpful for Devs; Thank you!
You're welcome
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)
@@ewgenbi Thank you
AAAAAAAAAAAAAAAAA thanks thanks. I've been waiting for this video
What would you like to see next?
@@MilanJovanovicTech Microservices)
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.
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
Would love to see this video but greatly expanded for the developer who is still trying to get a handle on the Identity library. Otherwise can you recommend resources to get up to speed, so I could recreate this without being a monkey on the keyboard? Thanks greatly.
Check out Anton's playlist: th-cam.com/video/ExQJljpj1lY/w-d-xo.html
First of all great video, Small question say you have another service which you need authorization for how would you use your current service to authenticate it?
When you say service you mean a physically separate service?
Very good! Thanks for sharing.
Most welcome!
love it! clear and simple! thanks!
Thanks! :)
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.
5:00 - Schema setup
5:46 - Schema looks like in DB
👍
Hi, thank you for the video. I don't know why they don't add some extra endpoints for managing roles associated with User when registering. What the tips in that case ? Implementing a custom endpoint in order to associate role with a user ?
Yep, have to make something custom
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
@@MilanJovanovicTech Tanks for help, but I have one more question. How I can extend the "register" endPoint for my User Class?
public class User : IdentityUser
{
public string? UserSurname { get; set; }
public string? Address { get; set; }
public DateTime DateOfCreation { get; set; }
}
Fire tutorial!! U the G
Thank you!
Thank you for video, i want to use it in clean architecture. But i have a question: where should i put creating, updating, deleting users and their roles?
Use cases in the application layer
@@MilanJovanovicTech Thank you so much!
We are really Looking forward to have a IdentityServer4 replacement. Is anything there similar to that.
Keycloak? Or pay for a license
What confuses me, if we are not implementing the registration process but just using the default how would you then use the provided /confirmEmail endpoint, in which step and where should i use 'sendgrid' for example to send a confirmation token to my user. ?
You can send the confirmation yourself, and it'll hit that endpoint. Or you can auto-confirm new users.
Thanks for the clear explanation video. But why use Docker? have to install Docker to run the app? it also seems that if you add Docker when creating the WebAPI app it will yield a nearly blank program.cs file.
Makes it easier to run the app on different machines
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
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
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.
I'd love to see this working with an external account like Google
Ok, that's a great idea for another video
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
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 do I get the cookie to my frontend? It works fine when I log in through Swagger, but not from my frontend.
The cookie is surely returned in the API response, you just need to save it
Forgot password, very large token received in email, how can we configure it to send may be a 6 digit code.
I'm not sure if that's something that is customizable
@@MilanJovanovicTech well that is, AddIdentityCore options=> options.token.PasswordResetTokenProvider = TokenOptions.DefaultPhoneProvider
Doing this has given me a 6 digit numeric code when calling usermamager.GeneratePasswordResetTokenAsync
But for some reason when i call the identity's forgot password endpoint it emails a 8 digit alpha numeric code
If i can somehow set the token provider to ToTpSecurityBasedTokenProvider that might help, but i cannot figure out how to do it yet
The password reset for mobile app users has to be a short code, as a standard practice
@@MilanJovanovicTechmoreover, i want to customize the content of the emails it is sending for registration or password reset etc,
e.g put my required html , company details etc
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
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
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?
Microsoft.AspNetCore.Identity 2.2.0 package is deprecated . What to use as alternative?
You can add a framework or project reference or in your csproj
Why do authorized endpoints return 404 instead of 401 if not logged in and using cookie authentication?
That's strange behavior
First of all thank you. Second, how can i exclude some functions from the public identityApi, ie, new users are not allowed to be register.
Sadly, there isn't an option for that
Can I integrate web api with external authentication service like google or facebook with this library, without blazor identity side or mvc ?
Yes
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
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?
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
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
Thank you milan!
You bet!
Is there a way to signup/signin using phone number instead of email, using identity?
Not sure
kinda a lot of config which works out of the box in django, any way to speed it up?
It's just a few lines of code, though?
@@MilanJovanovicTech yes, but the besxt code is no code ^^
Hello I cannot use parse this token in frontend to see user claims.
It's not a JWT
@@MilanJovanovicTech also it has other problems. It cannot be decoded like a jwt to see user claims. So i wrote custom login endpoint to get jwt token with claims
I really like your content :) How can I get the response in 08:27, when I want to use a custom controller method?
You can use the UserManager class
@@MilanJovanovicTech Thanks for the response, but I cannot generate a token with u
UserMsnager. For that I need an extra package..At least according to all information I found in the internet...
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
Could you explain why we need IdentityServer4 ?
When did I say we needed it?
is it possible to integrate this with social social auth to assign permissions to users login with google for example
I believe it's possible, check this: learn.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins?view=aspnetcore-8.0
Can we configure these generated end points
Nope :/
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 👌
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
nice content, thanks
You're welcome
how can i implement roles on top of this?
It's already there
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
Can you please milan make a video about chain of responsability pattern
Already covered it many times - with MediatR pipeline behaviors
Thanks ❤
You're welcome 😊
Any idea why i am getting the IEmailSender error?
Didn't register it with DI?
can i authenticate using username instead of email?
I think so, though I'm unsure (from memory) what needs to change in the setup
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
Cookie vs jwt with?
I usually work with JWT
@@MilanJovanovicTech cool, do you have videos about refreshing tokens using jwts?
А как использовать JWT?
Check out Microsoft.AspNetCore.Authentication.JwtBearer
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!
in my code give this error initials column
Did you run the migration?
But extending custom class not possible! probably .net 9 will fix that!
Any issues about that you're tracking, perhaps?
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 :/
its not beginner friendly
Refer to the MSFT docs then
What exactly is Not beginner friendly?! After 10 minutes you have a running auth-layer in your Application
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?
Why do you skip some parts of the video?????? I have to pause video to copy the code
Ok
❤❤❤❤❤❤❤❤❤❤
Much appreciated!
Too fast. I’m sorry
Ok
How to generate migration? if I knew all that I would not watch this video!!!!!
learn.microsoft.com/en-us/ef/core/managing-schemas/migrations
you're a little bit too angry, entitled and rude. Relax you're not going to go far with that kind of attitude
Here you go: learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli
@@MilanJovanovicTech oh wasn’t addressing you milan ;) my comment was for the original comment.
@@TitusM7 Just saw I didn't reply (I usually do) 😂