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
  • Наука та технологія

КОМЕНТАРІ • 118

  • @MilanJovanovicTech
    @MilanJovanovicTech  Місяць тому +6

    Get the source code for this video for FREE → the-dotnet-weekly.ck.page/aspnetcore-identity

    • @thofalbo
      @thofalbo 29 днів тому

      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?

  • @dailydoseofdotnet
    @dailydoseofdotnet Місяць тому +16

    Milan's videos' value per second is always so high, lol. Absolutely no fluff whatsoever.

  • @mikeutube7888
    @mikeutube7888 Місяць тому

    love it! clear and simple! thanks!

  • @jonahl9898
    @jonahl9898 Місяць тому +12

    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.

    • @zfold4702
      @zfold4702 Місяць тому +1

      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.

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому +1

      Awesome, thanks for adding this!

    • @kangabroo
      @kangabroo Місяць тому

      They are opaque bearer tokens, not JWT.

    • @dragannikolic568
      @dragannikolic568 Місяць тому

      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 :)

  • @DenisioRodrigues
    @DenisioRodrigues Місяць тому +1

    Very good! Thanks for sharing.

  • @arnelirobles
    @arnelirobles 14 днів тому +1

    wow. this makes things easier. i use to make the endpoints manually.

  • @JustCode512
    @JustCode512 Місяць тому

    Thank you milan!

  • @itirush2701
    @itirush2701 Місяць тому

    AAAAAAAAAAAAAAAAA thanks thanks. I've been waiting for this video

  • @Mig440
    @Mig440 Місяць тому +9

    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?😊

  • @Rahulsapkota
    @Rahulsapkota Місяць тому

    nice content, thanks

  • @Sharondevbd
    @Sharondevbd Місяць тому

    Thanks ❤

  • @mariomandzukic8676
    @mariomandzukic8676 Місяць тому

    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

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      Yes, but I typically like to keep separate contexts and schemas for Identity and my domain models

  • @yuravertsimaga6012
    @yuravertsimaga6012 Місяць тому

    Great, thanks! But can we use JWT here? or just Bearer?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      Bearer, it's not a proper JWT. That would have to be implemented separately.

  • @Davide-zx7ig
    @Davide-zx7ig Місяць тому

    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?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      No, Identity endpoints doesn't pick up the change

    • @Davide-zx7ig
      @Davide-zx7ig Місяць тому +2

      @@MilanJovanovicTech So what’s the point of using that endpoint if you cannot custom the json body?

    • @LucaAzalim
      @LucaAzalim 13 днів тому

      @@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.

    • @Davide-zx7ig
      @Davide-zx7ig 13 днів тому

      @@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

  • @yunusemreteke
    @yunusemreteke Місяць тому +3

    Hey I wonder how we use TwoFactorAuthentication in identity with using google or microsoft authenticator app can you make a video for this topic?

  • @aqorda
    @aqorda Місяць тому +1

    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
      @MilanJovanovicTech  Місяць тому

      ?

    • @ewgenbi
      @ewgenbi Місяць тому

      builder.Services.AddAuthentication(options =>
      {
      options.DefaultScheme = IdentityConstants.ApplicationScheme;
      options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
      })
      .AddCookie(IdentityConstants.ApplicationScheme)

  • @hozmannew896
    @hozmannew896 Місяць тому

    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
      @MilanJovanovicTech  Місяць тому +1

      It's not included automatically on the register endpoint

  • @tayyabshaikh3286
    @tayyabshaikh3286 Місяць тому

    we need more videos like this which covers full end to end steps

  • @nguyentrungkien1207
    @nguyentrungkien1207 Місяць тому

    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?

  • @hdjfgt
    @hdjfgt Місяць тому +1

    Why only run migrations on development? How do you apply them in other environments?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      Manually, and preferably with SQL scripts.
      In some projects, I'll use a tool to automate this. One example is RoundhousE

  • @chrisauret3785
    @chrisauret3785 Місяць тому

    Which layer would the IdentyUser exist in a Clean Architecture solution? And how would it affect other layers?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      Depends, do you want to use the AspNetCoreUsers table only, or also have your own?

  • @rodrigo-5967
    @rodrigo-5967 Місяць тому +2

    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

    • @10Totti
      @10Totti Місяць тому

      Is not possible.

    • @rodrigo-5967
      @rodrigo-5967 Місяць тому

      @@10Totti thanks, at least I'm no longer going to spend time finding how to do it

    • @piotrkowalski3460
      @piotrkowalski3460 Місяць тому

      @@rodrigo-5967 ​ you can implement your own register endpoint instead of relying on MapIdentityEndpoints

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      Should be possible through the Claims table in the database. I'd refer to the docs for that part.

  • @EvekoShadow
    @EvekoShadow Місяць тому +1

    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.

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому +1

      Auth is such a complex topic. I'm glad we have good abstractions in place.

  • @YI-gt7kh
    @YI-gt7kh 2 дні тому

    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).

  • @MahmoudSaed98
    @MahmoudSaed98 Місяць тому +3

    We want you to explain the Bogus library and an explanation of its use with unit testing using Mock

  • @326435ha
    @326435ha Місяць тому

    What do I need to adjust to use int as a key for all the generated classes

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      I believe it's IdentityUser, but check the docs for the exact syntax

  • @tomekres1021
    @tomekres1021 Місяць тому

    Can I integrate web api with external authentication service like google or facebook with this library, without blazor identity side or mvc ?

  • @YarnellCrew
    @YarnellCrew Місяць тому

    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
      @MilanJovanovicTech  Місяць тому

      Shouldn't this be done from the client side?

    • @YarnellCrew
      @YarnellCrew Місяць тому

      @@MilanJovanovicTech There is no client side, this is a pure server side Blazor app.

    • @YarnellCrew
      @YarnellCrew Місяць тому

      @@MilanJovanovicTech Sorry what do you mean from the client side?

  • @fredchess
    @fredchess 18 днів тому

    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?

  • @FrequencyModulator
    @FrequencyModulator 5 днів тому

    For example I don't want to allow users to register, is there a way to hide/remove this endpoint?

  • @wicho5401
    @wicho5401 Місяць тому +1

    I'd love to see this working with an external account like Google

  • @MostaSufa10
    @MostaSufa10 Місяць тому

    Is it possible to configure the generated token or its expires time?

    • @HedgarBezerra
      @HedgarBezerra Місяць тому

      Yes, it's. as you're adding the Bearer token to service collection, you can pass the configuration after the schema.

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      Yes

  • @hknk
    @hknk Місяць тому +2

    Is there a way to disable register endpoint?

    • @theentein
      @theentein Місяць тому +2

      No. You cant override. But You can redirect it to another page.

    • @10Totti
      @10Totti Місяць тому

      Middleware.

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому +1

      It seems no, which is tragic

  • @gibin.francis
    @gibin.francis Місяць тому +1

    In clean architecture landscape, where the User class should be placed

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      Domain

    • @gibin.francis
      @gibin.francis Місяць тому

      @@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?

  • @raman465
    @raman465 7 днів тому

    Could you explain why we need IdentityServer4 ?

  • @10Totti
    @10Totti Місяць тому +3

    Nice tutorial thanks. Too bad it's very limited if we want to do customizations.

    • @JollyGiant19
      @JollyGiant19 Місяць тому +2

      Yeah, that’s the worst part of it. It feels limited to POCs and demos

    • @amrswalha
      @amrswalha Місяць тому

      True, using these out of box authentication in real life can be a challenge if you want to customize anything.

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      It's not much different than integrating with an external IDP

  • @BJazz19
    @BJazz19 Місяць тому

    can i authenticate using username instead of email?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      I think so, though I'm unsure (from memory) what needs to change in the setup

  • @denissorn
    @denissorn Місяць тому

    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.

  • @ramytawfik9168
    @ramytawfik9168 Місяць тому

    Can you please milan make a video about chain of responsability pattern

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      Already covered it many times - with MediatR pipeline behaviors

  • @88guernica
    @88guernica Місяць тому +1

    Is it necessary to do all this if I am going to use something like OKTA/EntraID?

  • @segunbabalola7430
    @segunbabalola7430 Місяць тому

    Any idea why i am getting the IEmailSender error?

  • @PremiumAsh-jd3qd
    @PremiumAsh-jd3qd Місяць тому

    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

    • @10Totti
      @10Totti Місяць тому

      is not possible.

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      Sadly, you'll have to manage that on your own :/

  • @dzllz
    @dzllz Місяць тому +1

    Cookie vs jwt with?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      I usually work with JWT

    • @dzllz
      @dzllz Місяць тому +2

      @@MilanJovanovicTech cool, do you have videos about refreshing tokens using jwts?

  • @VikasSoam-uh1dl
    @VikasSoam-uh1dl Місяць тому

    in my code give this error initials column

  • @sebastianszafran5221
    @sebastianszafran5221 29 днів тому

    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!

    • @MilanJovanovicTech
      @MilanJovanovicTech  28 днів тому +2

      I will try to cover these questions in a future video

    • @sebastianszafran5221
      @sebastianszafran5221 28 днів тому

      @@MilanJovanovicTech Thank you! Forgot to add that I really appreciate your videos!

  • @muhdinmussema5854
    @muhdinmussema5854 Місяць тому

    But extending custom class not possible! probably .net 9 will fix that!

  • @yohm31
    @yohm31 Місяць тому

    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 ;)

    • @MilanJovanovicTech
      @MilanJovanovicTech  Місяць тому

      Why not use an external IDP then?

    • @yohm31
      @yohm31 Місяць тому

      @@MilanJovanovicTech why not. Which one do you recommend?