ASP.NET Core Web API Authentication and Authorization with JWT (Json Web Token)

Поділитися
Вставка
  • Опубліковано 21 лип 2024
  • In this tutorial we’ll setup a JWT (JSON Web Token) in an ASP.NET Core Web API, implementing Authentication and Authorization. We’ll talk about why it is important for your ASP.NET Core Web API to require authentication with JWT. From project setup to testing this entire process with Postman, by the end of this tutorial you will have a good idea of how to setup authentication and authorization in your .NET Core applications with JWT.
    Authentication with JWT is one of the most secure and most performant ways to secure data transfers between client and server. We’ll not only set up authentication in our ASP.NET Core Web API but we’ll touch on authorization and how different user security roles can access specific resources.
    Source code: github.com/iulianoana/jwt-dot...
    0:00 - Intro
    0:11 - Create a new ASP.NET Core Web Application
    0:30 - Install Packages
    1:55 - Setup appsettings.json
    3:10 - Setup Startup.cs
    7:30 - Add necessary models
    9:32 - Add API Controllers
    18:25 - Test Token Generation with Postman
    20:54 - Add UserController
    20:54 - Setup API to require Authentication
    28:50 - Setup API to Authorize requests
    Join our bi-monthly email squad: signup.codewithjulian.com
    Check out further resources: codewithjulian.com
    If you enjoyed this tutorial, please like this video consider subscribing for more content like this!
    Subscribe to my channel: / @codewithjulian
    Useful Links:
    JWT Token Explained: • What is Json Web Token...
    Packages:
    - Microsoft.AspNetCore.Authentication.JwtBearer (3.1.20)
    - Microsoft.IdentityModel.Tokens (6.14.0)
    - System.IdentityModel.Tokens.Jwt (6.14.0)
    String generator (for secret key): www.random.org/strings/
    Types of registered claims: datatracker.ietf.org/doc/html...
    Introduction on Jwt: jwt.io/introduction
    Old but good read: devblogs.microsoft.com/aspnet...
    Credits:
    - Sound effects obtained from www.zapsplat.com
    - Icons designed by www.freepik.com and www.flaticon.com/
    - Images from the artists on unsplash.com/

КОМЕНТАРІ • 245

  • @hello-matthew
    @hello-matthew 2 роки тому +19

    Thank you - this was perfect! I liked the fast pace and length of the tutorial. Your tutorial is uncluttered, clear, and to the point. Keep making more!

  • @monaziralam1862
    @monaziralam1862 5 місяців тому +1

    Clear, crisp and quality teaching by saving the time too, great man!

  • @programmingcake8910
    @programmingcake8910 2 роки тому +2

    This is the best tutorial on JWT Authentication and Authorization I've ever seen so far, Thank you so much for your efforts.

  • @bloggrammer
    @bloggrammer 2 роки тому +3

    Great video, @Code with Julian. Well done.
    In the Authenticate method in the LoginController class, there's no need to check for null. The Linq FirstOrDefault(...) will return null if the user with the conditions is not found, otherwise, it will return a user model.
    Thank you for the video.

  • @okeluelazarus7062
    @okeluelazarus7062 6 місяців тому +2

    Bro this tutorial just saved me today, thanks so much, your calmness and pace of everything in the way you teach is excellent please keep it up

  • @rajkumararora7366
    @rajkumararora7366 4 місяці тому

    Complex matters explained with simplicity. Thank you for sharing your great work!

  • @STUPIDYOUTUBE_HIDINGMSGS
    @STUPIDYOUTUBE_HIDINGMSGS 2 роки тому +9

    Your tutorial is amazing, very much what I was looking for to create a production-level API with authentication, you explained stuff clearly, very detailed and well-explained and code is easy to follow without complexity and unnecessary filler codes that can be used as a template in corporate APIs. I've had paid subscriptions on Pluralsight and LinkedIn Learning, but the way you teach and this example topples most of the ones I've seen in those paid online courses where all they've done is pad their tutorials with unnecessary junk of codes to make it longer but pretty difficult to implement! I've subscribed and will definitely watch all your videos, thanks and keep it up!

    • @CodeWithJulian
      @CodeWithJulian  2 роки тому +5

      Hey Brad! First of of, thank you very much for your kind words. I wish you guys would feel the same way I feel when you leave these nice comments. It truly brings joy and motivation to keep going!
      Secondly, I'm happy that you've found this tutorial valuable, I try to cut the fluff as much as possible, without compromising on essential details on the subject.
      Thank you again for your comment and I hope you have a great day!

  • @justraccoon3047
    @justraccoon3047 2 роки тому +5

    Omg Bro, you're incredible. I tried to add this functionality for a very long time and nothing ended with success. But your video solved my problem just in 30 minutes. And one more thing, your English is very understandable for non-native speakers. Thank you a lot!

    • @CodeWithJulian
      @CodeWithJulian  2 роки тому +1

      Thanks, really appreciate your feedback, happy it's been useful!

  • @muhammadhydaque2976
    @muhammadhydaque2976 10 місяців тому

    Just passed by that one and it was so straight-forward for me. Keep it up and thank you for such an awesome content

  • @kamiladewale5426
    @kamiladewale5426 2 роки тому

    Thanks so much Julian for making me understand this easily. Subscribed and will keep following updates here.

  • @insane101gaming7
    @insane101gaming7 2 роки тому +1

    Thank you for the simple and effective explanation. I was really stuck on how to decode jwt token to get user detials, and didnt got any perfect solution for this problem. But you did a great job at this.

    • @CodeWithJulian
      @CodeWithJulian  2 роки тому

      Glad the tutorial has been helpful to you! Thanks for sharing that!

  • @zahiyoussef2551
    @zahiyoussef2551 4 місяці тому

    the best on youtube that explaine it , the exemples of success and failings , helps a lot , keep it up sir

  • @mrg4545
    @mrg4545 2 роки тому

    It's the subject I've been looking for for a long time and the best resource I've found. Thanks...

  • @mathewstarr8501
    @mathewstarr8501 2 роки тому

    This video was very helpful, thanks for this. Please continue to create more content.

  • @anurag0304
    @anurag0304 Рік тому +1

    short, to the point, and a nice tutorial. Kudos to Jason and Elysse

  • @JollyGiant19
    @JollyGiant19 5 місяців тому +1

    This is very well done, thank you so much for making this!

  • @albertovelasco495
    @albertovelasco495 2 роки тому

    Thank you, Julian, very easy to understand.

  • @sinan-hoca
    @sinan-hoca Рік тому

    I was looking for this for a long time. Watched tons of garbage. Finally I've found the exact video I was looking for. Every single thing I need is in the video. Thanks for sharing this useful tutorial.

    • @CodeWithJulian
      @CodeWithJulian  Рік тому

      Thanks for your feedback! I'm glad the tutorial was helpful to you.

  • @mohammedbenlaiter2046
    @mohammedbenlaiter2046 2 місяці тому

    you saved my graduate project
    thank u

  • @theweasel7905
    @theweasel7905 2 місяці тому

    Thank you for the great tutorial!

  • @kareempr007
    @kareempr007 10 місяців тому

    Thaks a lot the way of your teaching is so clear and straightforward.

  • @sebastianlopez5979
    @sebastianlopez5979 2 роки тому

    This is a great tutorial. Clear explanation and good examples. Thank you very much.

    • @CodeWithJulian
      @CodeWithJulian  2 роки тому +1

      Thanks Sebastian! Happy it's been helpful!

  • @ashutoshsingh5568
    @ashutoshsingh5568 2 роки тому +1

    Hey Julian, thanks for this informative video. I appreciate your efforts to make this useful content. I liked how you explained all about JWT & authentication in steps.
    Thanks and keep sharing.
    Edit: I subscribed the channel. 😊

  • @syedalirizvi6162
    @syedalirizvi6162 Рік тому

    Brilliant Explanation you made this topic so simple by your explanation

  • @bongoSLAP1
    @bongoSLAP1 2 роки тому +4

    If you are using .NET 6, add this to your program.cs file
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
    options.TokenValidationParameters = new TokenValidationParameters
    {
    ValidateIssuer = true,
    ValidateAudience = true,
    ValidateLifetime = true,
    ValidateIssuerSigningKey = true,
    ValidIssuer = builder.Configuration["Jwt:Issuer"],
    ValidAudience = builder.Configuration["Jwt:Audience"],
    IssuerSigningKey = new SymmetricSecurityKey(
    Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])
    )
    };
    });
    var app = builder.Build();

  • @arjunm.r8641
    @arjunm.r8641 2 роки тому

    @Code With Julian Thanks for the video. This tutorial gave me an idea about JWT tokens implementation

  • @diyahabdo
    @diyahabdo 2 місяці тому

    That was so helpful ,Thank you so much .

  • @pallyweb
    @pallyweb 2 роки тому

    Simply Awesome. Thanks for creating awesome tutorial. Keep great work up.

  • @sebastiantenorio8602
    @sebastiantenorio8602 2 роки тому +2

    Great Tutorial, you should post one where you refresh the tokens.

  • @sustainedcruelty
    @sustainedcruelty 2 роки тому

    Thanks a lot for making this, it really helped me out!

  • @zoal
    @zoal 2 роки тому

    This was exactly what I needed. Great job. Look forward to more.

    • @CodeWithJulian
      @CodeWithJulian  2 роки тому

      Thanks for the feedback! More to come shortly!

  • @javierpetrozzi
    @javierpetrozzi Рік тому

    Thanks Julian, you're very clear and tbe video is very useful.

  • @BrandonLackey
    @BrandonLackey 2 роки тому

    Thank you. This was super helpful!

  • @xSal2oHD
    @xSal2oHD 2 роки тому +1

    Perfect explanation , straight to the point ! Thank you

  • @vipulshrivastava1069
    @vipulshrivastava1069 3 місяці тому

    Valuable lesson. Thanks Julian.

  • @argniests5357
    @argniests5357 2 роки тому

    Thanks for the video. Good stuff!

  • @raggardy
    @raggardy 2 роки тому

    Fantastic explanation Julian. Subscribed. Nice one, mate

    • @CodeWithJulian
      @CodeWithJulian  2 роки тому

      Thanks for feedback! Happy it's been helpful!

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

    Thank you so much, it helped me a lot

  • @k.eshwanth7752
    @k.eshwanth7752 2 роки тому

    Everything in one go, Thanks for the video.

    • @CodeWithJulian
      @CodeWithJulian  2 роки тому

      Thanks for the feedback, glad it was helpful!

  • @JoeScottish
    @JoeScottish Рік тому

    Thanks..... I've now created my first Web API thanks to you

  • @trilokpandey2156
    @trilokpandey2156 Рік тому

    Nice, you explained necessary code

  • @kurtmullner3488
    @kurtmullner3488 2 роки тому

    Perfect, I will use it for my apprentices. Thanks a lot!

  • @zhangrui2664
    @zhangrui2664 2 роки тому

    Your video is very very useful , Thank you!

  • @user-qe2wd8ri9m
    @user-qe2wd8ri9m 9 місяців тому

    Simple and Neat explanation, Great Job

  • @tiagobiker
    @tiagobiker 2 роки тому

    Excelent tutorial, very precise. Thanks !

  • @moralstories8134
    @moralstories8134 2 роки тому

    Thank you so much …this tutorial helped me in my interview …

    • @CodeWithJulian
      @CodeWithJulian  2 роки тому +1

      That's wonderful news! Hope you got the job 🥳

  • @taduribhargavi4112
    @taduribhargavi4112 6 місяців тому

    Amazing Tutorial

  • @nginakilonzo6929
    @nginakilonzo6929 8 місяців тому

    You are so awesome. Thank you! This has been so helpful

  • @gayanath009
    @gayanath009 Рік тому

    Amazing work. Thanks for the great explanation. May all your work success and shine bright..

  • @thienpham1838
    @thienpham1838 2 роки тому

    Thank you very much! This is useful video

  • @AjithChanaka
    @AjithChanaka Рік тому

    Thanks, it is a clear teaching.

  • @kamranellahi3517
    @kamranellahi3517 2 роки тому

    You are doing great work
    Keep the good work goin brother

  • @kaiomaciel8916
    @kaiomaciel8916 Рік тому

    that was awesome, Julian! You reminds me the dude from Silicon Valley TV Show xd. I rly appreciate for the video's content.

    • @CodeWithJulian
      @CodeWithJulian  Рік тому +1

      Haha beautiful, thanks! Glad the tutorial was useful!

  • @RodneyEllisAU
    @RodneyEllisAU Рік тому

    this is one of the best tech videos i've watched for a long time!

    • @CodeWithJulian
      @CodeWithJulian  Рік тому +1

      Thank you for your feedback! I'm happy it's been useful to you!

  • @patrykklimas4398
    @patrykklimas4398 2 роки тому

    Thanks for this video!

  • @blagovestkolev7716
    @blagovestkolev7716 Рік тому

    It`s nice tutorial ! Not too long, but very useful ! Thanks. Subscribed.

  • @mesutdemirci7933
    @mesutdemirci7933 Рік тому

    Thank you - this was perfect!

  • @anupkumar601
    @anupkumar601 Рік тому

    Very clear and easy to understand ..Thanks

  • @ahmedsaeed5149
    @ahmedsaeed5149 Рік тому

    Thank you so much for your excellent tutorial 🖐😄

  • @ROLOGamingOfficial
    @ROLOGamingOfficial Рік тому

    Can you authorize controllers instead of doing one end point at the time for admins/other-users?

  • @rondolfopresilla6876
    @rondolfopresilla6876 Рік тому

    Best tutorial on the subject, thank you bro

  • @ariefmuizzuddin1165
    @ariefmuizzuddin1165 7 місяців тому

    hi, i have a question. can i use jwt as authentication, then i have 2 client which is web and mobile apps. so when user log in in web it will get access token for that web client, and when the same user log in into mbile apps it will get access token for that app client. therefore if 1 of the client is logged out by the user, the other client shouldnt log out. just want to know is this still correct practice. because i have confused with identityserver, AOuth 2.0

  • @muharremekimci2208
    @muharremekimci2208 10 місяців тому

    thank you so much 🙏

  • @user-cd2ls5rk9l
    @user-cd2ls5rk9l Рік тому

    man, you are awesome. Thank you very much for this video. You are a hero that saved me a lot of time!

  • @amnaterzic5331
    @amnaterzic5331 2 роки тому

    This was so precisely explained, well done. Thank You so much for this video. I have one question. If I want to make connection to Postgresql database with Visual Studio, what should I do?

  • @sidraidrees7282
    @sidraidrees7282 Рік тому

    any idea, why I am getting below error when I try to access API having [Authorization]?
    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).

  • @deepanshukumar3943
    @deepanshukumar3943 2 роки тому

    Awesome Awesome just awesome... Amazing video

  • @ertan952
    @ertan952 2 роки тому +12

    there is very important point for UseAuthentication method call. The calling order should be like that for net5 and upper versions,
    app.UseAuthentication();
    app.UseRouting();
    app.UseAuthorization();
    Otherwise you will continue to get 401 error due to middleware execution order.

    • @kimjoshuaespanol
      @kimjoshuaespanol Рік тому

      Thank you so much for this help !

    • @PrathikaSuvarna
      @PrathikaSuvarna Рік тому

      Thank you so much for this comment

    • @divyanshukumar5004
      @divyanshukumar5004 Рік тому

      thanks a lot man. I was facing the 401 issue and I really worked so hard to fix it but I was unable to fix it. So lastly I start reading the comments and found urs. Thanks a lot 🎉

    • @IlyaArlenka
      @IlyaArlenka 5 місяців тому

      Thank you so much!

  • @eyalankri
    @eyalankri 7 місяців тому

    Thank you!

  • @JAH7070
    @JAH7070 2 роки тому

    thank you so much for this tutorial!!

  • @fieryscorpion
    @fieryscorpion 2 роки тому +1

    Any reason why you didn’t choose .NET 6 since that’s already released and has so much of performance improvements?

  • @yogitarameshgate3930
    @yogitarameshgate3930 2 роки тому

    Worked perfectly! some detailed explanation about JWT settings might have helped more in understanding internals

  • @Harsh-Deshmukh
    @Harsh-Deshmukh 9 місяців тому

    Short and to the point, Thanks Julian. I have 1 doubt .what is the significance of creating new instance of UserModel in getCurrentUser method in UserController?

  • @RajVadla
    @RajVadla Рік тому

    Hey, Can you please help with encrypting and decrypting the JWT? It doesn't seem to work in dotnet.

  • @laxregula9007
    @laxregula9007 Рік тому

    Great tutorial. Loved it!

  • @ramiroalegre8183
    @ramiroalegre8183 2 роки тому

    Excellent tutorial !!!, my english is basic and i use the automatic provide for youtube translator in spanish and is a really nice, this is because u audio is so god. Thanks :)!

    • @ramiroalegre8183
      @ramiroalegre8183 2 роки тому

      Also because the code is understood regardless of the language in which you speak

  • @jeff_9074
    @jeff_9074 2 місяці тому

    I created an asp.net core mvc web application for individual accounts. I abstracted out EF core, and have all the authorization/2FA, pw reset, email authorization, account lockout... etc, handling in place. I eventually would like to create a mobile application to go with it. I planned on having the user use the website for setting up/editing their account personal details, and password changes/reset. I figure right now is a good place to create the Web API and start configuring now common data access/changes the web app and mobile application will use. What is the best way to approach this, and leave the current authorization/authentication in place for the web application, but have it also authenticate to the web api? Thank you!

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

    you are amazing can you do a vedio on sending requests from a client react app side to the api,i would like to see how it works with jwt,am interested in the logic.Otherwise your tutorial is the best on jwt

  • @phongnguyenphamthanh3106
    @phongnguyenphamthanh3106 3 місяці тому

    I did exactly like you, not missing even a single syntax but keep receiving the "missing of Kid" which is KeyId. Can you help?

  • @freeeasyprogramming5151
    @freeeasyprogramming5151 2 роки тому

    Big up brother , its a great tutorial

  • @gowthamtj8533
    @gowthamtj8533 10 місяців тому

    wow amazing tutorial

  • @cissemy
    @cissemy 2 роки тому

    Great
    I see you added api controller to razor page project.
    How can I make use of the 2 controllers in the razor pages ?

  • @adnanshafi6630
    @adnanshafi6630 2 роки тому

    Excellent Sir
    doubts are cleared now

    • @adnanshafi6630
      @adnanshafi6630 2 роки тому

      @@CodeWithJulian kindly also share about real world Example for ,Net core Api

  • @Aegisman
    @Aegisman 2 роки тому

    Hi Julian, tbh, first video that I watched that went straight to the point w/o to many irrelevant informations, great job. Small question, how much of this is relevant for .NET 6 API (Not minimal)

  • @michaelacevedo172
    @michaelacevedo172 Рік тому

    great Tutotial is just that i need, please have a question how pass this auhorization in a method of mvc, i tell you i put the [Authorize] in one method but altougth im autheticated the response is unauthorized please and thanks for your time

  • @prathameshshende4
    @prathameshshende4 Рік тому

    where to provide jwt token into code after generate? I seen you do this in postman.

  • @dasmaffin1633
    @dasmaffin1633 Рік тому

    Does this also work when my project type is Web Api and not web application?

  • @ashrafdar
    @ashrafdar 17 днів тому

    excellent!!

  • @tiendungnguyen4689
    @tiendungnguyen4689 Рік тому

    great, I love it

  • @dotnetfullstack3217
    @dotnetfullstack3217 Рік тому

    Best Video to learn about JWT TOken Authentication and Authorisation
    1. Simple explanation
    2. Clear command over topic
    3. step by step by explanation
    4. Working code link

  • @Allyourneedsmet
    @Allyourneedsmet Рік тому

    Please for the love of all things good, where can I find the article on this within the microsoft authentication. I would like to read on it for indepth details

  • @hieu_nguyen_20
    @hieu_nguyen_20 10 місяців тому

    Where can i get JWT key value in appsetting.json ?

  • @MuhammadShaheryar-dx8tj
    @MuhammadShaheryar-dx8tj Рік тому

    Great video :)

  • @selcukyazc8450
    @selcukyazc8450 2 роки тому

    nice video, thanks for everything :)

  • @malikbrahimi7504
    @malikbrahimi7504 Рік тому

    What's the difference between using this and identityuser from identity package?

  • @sponzorusa8660
    @sponzorusa8660 2 роки тому

    Thank you 😁

  • @khubaibirfan9215
    @khubaibirfan9215 Рік тому

    What if i am used to asp net core project not api?

  • @alishady87
    @alishady87 Рік тому

    Does this also work with .Net 6 ??

  • @adnanshafi6630
    @adnanshafi6630 2 роки тому

    Sir kindly describe how to put in cookie and using after the login?