Similar Posts

Leave a Reply

Your email address will not be published.

43 Comments

  1. Really enjoying your blog so far.
    Already went trough Onion architecture, Blazor and some other of your guides.
    Any chance that you will do Event Sourcing or microservices? Would be awesome 🙂

    1. Thanks for your time and feedback. Yes, Microservices is already on my TO-DO list. It may take some time to roll it out, as lot’s of research and writing is needed.

      Thanks and regards

  2. Hi Mukesh,

    Well instructed and detailed post. Thank you very much for sharing it to the community.
    One question, any plan to write Identity Server 4 along with Asp.net Identity and JWT ?

    1. Hi Gopal, Thanks for the feedback.
      Yes, Identity Server is on my TODO list already. Since it is quite a vast topic to cover, with various auth, I may post it as a series in a few days. Will keep you posted.
      Thanks and Regards

    1. Hi,

      you can extract the userId and other claims from the token using HttpContextAccesor. Here is a sample.

      var email = string.Empty;
      if (HttpContext.User.Identity is ClaimsIdentity identity)
      {
      email = identity.FindFirst(ClaimTypes.Name).Value;
      }

      However, I guess there is already a class that get the current userId. It’s at CleanArchitecture.WebApi/WebApi/Services/AuthenticatedUserService.cs
      UserId = httpContextAccessor.HttpContext?.User?.FindFirstValue(“uid”);

      Regards

  3. Hi Mukesh! this has got to be the best tutorial on how to implement JWT authentication, how ever i have an issue that i no longer can log into my webapp normally, is it possibel to use Session and jwt authentication at the same time, and if so how?

  4. Hello. I am a bit confused. what is the difference between JWT authentication and Identity server 4. If I understand, Identity server 4 uses as Tokens the JWT ones. So, what should we use ?

  5. how to we authorize based on permission tree

    for example,

    there are product feature (CRUD)
    – permission should be create, read, update , dellete permission

  6. Thanks for your effort, we do appreciate I’ve learned from a lot better than courses
    Could i you make a guide to signalr with identity if it suites your time ?

  7. How do you save this token in a cookie? or is that unnecessary once you’ve implemented the Refresh token in the next chapter?

  8. Hi Mukesh,

    Your Clean Architecture API refresh token implementation is not completed.
    I think I can complete your implementation via this article, can I?

    1. Hi, yes you can. However, I am not going to be continuing to contribute to that project anymore. I will be building up a new Project for .NET 5 WebApi Clean Architecture soon. The idea is to have a separate repository collection with a .net API and multiple other clients starting with Angular and Blazor. Probably React and Vue down the road. Any suggestions? Here is where the sources will be available – https://github.com/fullstackhero . I will be getting started with this project in a month.

    2. Hi Serkan,

      I am following this awesome Tutorial by Mukesh. Did you get chance to complete the Clean Architecture API refresh token implementation.

  9. Hi Mukesh,
    Thanks for this usefull guide. I’m following it but when i tried to generate the migration and database (commands) the DB is created empty. I checked the Startup.cs class and i have the same than you, Do you have any idea why it may happen?

  10. Hello Mukesh, great tutorial.
    Quick question:
    How to implement some built-in features asp.net core Identity in the JWT? Such as two-factor authentication(2FA) or locking the user account.
    Can you post about this?

  11. hey thanks for sharing this!!!
    I’m trying to run it and I can’t seed the default user, it throws an exception it says:

    “The INSERT statement conflicted with the FOREIGN KEY constraint \”FK_AspNetUserRoles_AspNetUsers_UserId\”. The conflict occurred in database \”ApiDB\”, table \”dbo.AspNetUsers\”, column ‘Id’.\r\nThe statement has been terminated.”}

    I tried to generate some random string for user id but didn’t work 🙁
    any suggest? thanks again!!!!

    1. var userWithSameEmail = await _userManager.FindByEmailAsync(model.Email);
      if (userWithSameEmail == null)
      {
      var result = await _userManager.CreateAsync(user, model.Password);
      if (result.Succeeded)
      {
      await _userManager.AddToRoleAsync(user, Authorization.default_role.ToString());
      }
      return $”User Registered with username {user.UserName}”;
      }
      Just look at this piece of code even if the result is failed it will still return the user is registered.

      1. Hi Azam,

        Did they give you an answer? I have the same error. I would like to know if there is an article where they fix it. Thx!

  12. Trank you very much from Venezuela. I was able to implement this tutorial in a project .net 3.1 WebApi Onion architecture in a few hours.

  13. Thank you for the article, it taught me a lot of new things.

    I have a problem with how you’re adding a role to a user, though. In practice, I’m an administrator and I want to add a role to a user. I won’t have their password, though. The function should just take the user name and role you want to add without a password.

  14. Dear Mukesh,
    Great Tutorial. I just tried your tutorial on .NET 6. However default user was not created until I made the following tweaks to your code. This is because firstname and lastname were created as compulsory or mandatory fields when migrations were applied.

    Authorization.cs
    public class Authorization
    {
    public enum Roles
    {
    Administrator,
    Moderator,
    User
    }
    public const string default_username = “benjaminsqlserver”;
    public const string default_email = “benjaminsqlserver@gmail.com”;
    public const string default_password = “Password_9.”;
    public const string default_firstname = “benjamin”;
    public const string default_lastname = “fadina”;
    public const Roles default_role = Roles.User;
    }

    ApplicationDbContextSeed.cs
    public class ApplicationDbContextSeed
    {
    public static async Task SeedEssentialsAsync(UserManager userManager, RoleManager roleManager)
    {
    //Seed Roles
    await roleManager.CreateAsync(new IdentityRole(Authorization.Roles.Administrator.ToString()));
    await roleManager.CreateAsync(new IdentityRole(Authorization.Roles.Moderator.ToString()));
    await roleManager.CreateAsync(new IdentityRole(Authorization.Roles.User.ToString()));

    //Seed Default User
    var defaultUser = new ApplicationUser { UserName = Authorization.default_username, Email = Authorization.default_email, EmailConfirmed = true, FirstName=Authorization.default_firstname, LastName=Authorization.default_lastname, PhoneNumberConfirmed = true };

    if (userManager.Users.All(u => u.Id != defaultUser.Id))
    {
    try
    {
    await userManager.CreateAsync(defaultUser, Authorization.default_password);
    await userManager.AddToRoleAsync(defaultUser, Authorization.default_role.ToString());
    }
    catch(Exception)
    {
    throw;
    }

    }
    }
    }