How to secure Web API in .NET Core using JWT Token

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello everyone welcome to the ITV Descamps I'm your host after update and in this video we are going to learn how we can implement and secure our Web API in dotnet called using GWT token the most popular JSON web tokens also known as JWT and we are going to see how we can do that I'm in my videos through 2019 so I'm gonna go to the help menu about and I'm using the community version which is study 2019 so what I'm going to do is I'm going to start a very simple new solution or a new project rather and I'm gonna say SP dotnet core web application I'm gonna say this without net core web application and choose next I'm using c-sharp application and I'm going to say Web API demo I'm going to hit create so it's going to display a dialog box with all the templates and here we are going to select API we have we have other companies as well web applications MVC and we also have an empty one so to start with I'm going to select API it gives us the boilerplate code and I'm going to choose SP dotnet core 3.1 which is the latest one and the framework we're going to choose the torte net core so with that thing selected I'm going to click on the create button leaving everything at this it's going to go ahead and create a web project for me Web API project for me it's going to take a little while setting up the project and the initial stuff and if I go over to my solution Explorer that is our solution right there and as you can see it has the startup file the program file and it has given us a test out of the box controller which is just called the weather forecast controller right and if I leave everything as this and just change a couple of things and if I leave everything as is and click on the start button it's going to go ahead and launch this in my Chrome browser which is set as the default if I resize this so that you can see what's happening behind the scene and it is displaying us all this information that is looking good our Web API is working so let me just go ahead and energy obtain the out of the box we get just one controller is called weather forecast controller and when we see the values in your browser we get this JSON what I can also do is just grab the URL and if I open up my postman and just check this URL in there and while my project is running if I just hit sane will get all that information in a nicely formatted I haven't as you can see I haven't specified any authorization right now it doesn't have any authorization added to it and just the you know the default header we don't even specified any custom header for us it's just a simple get and we get all this information to what we would like to do is somehow secure this endpoint so that you can only access it an endpoint if you had the right GWT token so let's see how we can implement that the first thing or the easiest way to authorize or what the easiest way to secure any endpoint is by just is by using one statement on the top of your endpoint and that is if I stop this one so that's it this is the endpoint we are calling right and that is just by adding the authorized keyword and of course authorize is not recognized because they need to import the proper namespace appear that it save and if I hit the run button again let's see if you get the information back or not just going to go ahead and process the information for us and try to retrieve the data looks like it did not work because it says no authentication scheme provided or if it is not very clear I can copy the URL go back to my postman actually this is my previous request which had the data with 200 ok now if I hit the send on the same endpoint let's see what we get as you can see we are getting some sort of an error but we are not able to get to the resource it is saying is that we have specified the authorized keyword but we haven't specified any authentication mechanism or authentication scheme rather so we have specified this one but we have been told our Web API how we would like to set up the authentication scheme on this application let's see how we can implement that first things first let's add a couple of neat packages you got the right it is the JWT packages so let me right click manage NuGet package it opens up this dialog box and here I'm going to search for I'm going to say JWT and if I dismiss this solution Explorer so the wicket see more so we are going to download this bit and this has got 91 point for millions at the time of this recording I mean this is really popular so let me go ahead and click on the install button it's gonna go ahead and do all the installation of the necessary files I'm gonna pause the video so that you don't to wait for it to do the installation all right we get this prompt to accept the license of course as we all do we just simply accept a license or make sure to read if you would like to I'm gonna click on accept and it's going to install the necessary files and looks like this bit is now installed if you would need another package is called JWT mmm Peter which is actually it was right there which is this one it has chords 7.7 million downloads this is also required package when you would like to do over authentication and as you can see the description it is if you don't read called middle world it enables an application to receive open ID kind of better talker so this is also required as part of our authentication process let me go ahead and click on install accept and this is also installed so let's verify if it was installs verify the package and as you can see under the dependencies under the dependencies I've got these two files added GWT builder and a JIT in the token okay so those package is installed not the way let me proceed to a very important file which is like the heart of this dotnet core solution and that is called the startup file alright so as you can see we do not have any authentication added world what we have the authorization but we do not have any authentication process we do not have any GWT configured here in the configuration service so let me go ahead and add the kwt configuration in the configured service section so I'm going to just paste in the code that I have and then I'll walk you through as to what it does so that you don't have to watch me type that whole section it will just save time I'm going to hit ctrl V because I have that code to my clipboard and this is what we have right now so what we are telling our dotnet core API is add this authentication so we are saying in the services add the authentication service and we are setting up some properties in here so so that's one bit and here we are telling our web api is to add an authentication and what is the authentication scheme there is a JWT authentication now every JWT authentication has to have an audience and fewer and a sign-in key so what we are saying here is the signing key signing key is nothing but a secret a secret that is used to verify the signature now let's configure this bit in here so we'll configure this bit in a moment and then we are saying okay validity sure it sure is who is issuing the GWT token so we would like to add that flag as well Bella did the audience audience is the Internet audience who this token is intended for so here we have few things is specified in here the valid issuer here is this value now where did I get this value from if I go to project properties in the debug I've got this one and the very date audience audience is also this one because I'm going to be generating token from this box and the audience is also this box let me explain this to you what the issuer and audience is I've got this PaintShop thing in here so if I were to let's say we've got two and it is in here right and here let's say we have your server let's say right and we have secured three source right and and here we have let's say client for example and this would become the issuer and this would become the audience and then we do generate this one so this generates the token generate the JWT token using the same secret key so the client or the Sherwood issue or generate or issue a JWT token using the same secret key that is configured in here I hope you know what I mean but it may be a bit hard to understand I'll show this to you in a video that will clear things up alright so we talked about the signing key signing key is like a secured password or something so we are getting some squigglies so let's add some necessary namespaces so it has added that and this sign-in key we haven't yet specified that so let us configure that we can do that right here it can be a private member of the class so I've got some quote in my clipboard I mean place that in here all right so this is your key let me add necessary namespaces and what this will do is this would generate a symmetric security key now a symmetric security is beyond the scope of this video but just in short a symmetric key is the type of in decryption scheme in which the same key is used both to encrypt and decrypt messages now line number 20 this one can be well it can be stored in a secure location it amend this value in here I mean this value in here this can be stored in your back contact file or a secure rep Quantic file you can give the values or in app settings while somewhere so that if you want to change you can always come and change without having to modify your classes so so with the authentication bit here added I'm going to save it and let's run it and let's see what we get all right now we get for one message just let's copy this let me put this in my postman and now we get 401 rather than some 500 error saying that the authentication schemes not specified so now we get the proper 401 error because what we're trying to do is we are trying to access a resource which was set as secured in the last video and that resource is this one we're trying to access this resource right there's the name of the controller there's you know the controller right and we are getting the 401 authorized because we added that authorized attribute in here so looks like we are looking good now there's one more thing that I would need to add in my starter class if I close this one here in our configure we are saying use authorization but so in addition to the authorization you will also like to add use authentication because authorization is telling what resources the users have access to but authentication would tell me if you are who you claim to be who you are I'm going to say app dot use authentication just to keep things really really safe and secure alright this is now in place now all we will need to do is generate a JWT token and in our get resource action we are going to add that jwg token and we'll see if we can access the resource let me add a new folder we'll just call that helper folder and inside of this ok we're going to create a class that would generate the JWT token for us if you are calling an application and you would like to see how we generate the JWT ticket I'm going to right click just add a helper class which will which will generate or JWT token for us let's call it JWT token I've got a code in my clipboard I'm going to paste that in here so that you don't have to watch me type that whole thing it will only save time so and then I explain to you what this code does and we'll add the necessary namespaces so let me add the namespaces so that we don't get this quickly so what are we trying to achieve here what we are trying to do is we are trying to generate a token that can access this resource which is which is a secured resource right and this API has got authentication in place with this security token so when you're trying to access our resource which has the authentication in place and it is using a secret key which is this and when you generate a JWT token your token should also match the same secret key so that it would be like for like because I'm using the same solution to generate the JWT token and then access the resource and here I've got one static method so because I have got the static method I would also like to set this class as the static I'm gonna save it okay so what we're doing is by specifying the credentials and we are using the SH a algorithm could generate our token and there's the credentials and this credentials is used in the header section and then we have this payload and to better understand how this thing is working you know the hydropower payload part let me take you to the JWT dot I your website and I'm on the home page of the JWT dot IO and if I scroll down this is our JW t on the left hand side and this JWT contains three parts the header bit which is in red and then the payload which is in the pink remember pay me for payload P for pink well that's one way to remember that bit and then we had the signature which is in the blue right here so what we're doing right now we are generating this token and we are working on the header part and what is the header bit he had a bit is disparate and we are saying the algorithm is have it a 256 the algorithm is this one to help you fix and then we have the payload section and the payload what we're doing is yes configuring our custom payload the subject the name these are the custom claims so inside of this payload so if I could take you back to the website so we have this payload and these are referred to as claims and and if I hover over it says subject home this token refers to it can be you know any value that you want in here and then the name of the token is 4 and then the issue at and as you can see the issue at has the UNIX epochs time it while the time here is in the integer date/time that's what I'm doing so so I don't have the issue add I can have the issue add bit it only tells me when the token was generated in the payload I'm specifying the subject the name the email address and the expiry all it is saying is this token is valid for how long one this is going to expire and here it is expecting the value in integers and I've converted this to actual just add one minute I need to say one minute not sixty all right so this is saying that this token is going to provide it for one minute or 60 seconds so I'm getting the date/time in here and I'm converting that to an integer time and well this is also referred to as epoch that we saw and here right at the time should be represented in epochs time or unix time and I've got issuer specified here the issuer I mean I'm using the same solution the issuer is using the same port as the resource so I'm going to say issuer that and then we have the audience is specified I'm the audience is also the same in here so let me make sure that it is the same for four three four - four three four - yep that looks about right and then we have the payload information and then we are generating and we are creating this GWT security token object I am passing in this header and payload information and then we are adding this security token handler which actually writes the token or generate the token so this is the line that does the magic looks like I'm missing a curly braces where at that that fixes that so to rephrase what we're doing here is this is the diagram but I want you to see this is a diagram that I want you to see so this is with the secured resources and this is your client now now for the demo purposes I'm just gonna copy this in here so for the demo purposes our server is on the spot right so I'm gonna just say this is the audience and this is the issuer so both the audience and the issuer are sharing the same port or they are part of the same solution so just for this demo purposes so sure is that so this is the server that is issuing the JWT and the audience is that so audience information and the audience is where the resource is it exciting audience is the address of the resource and the sure the party generating the JWT all right hope that clears something and then we have this bit we are just specifying we are just creating an object of the GWT security token as explained before and we pass in the header and the payload information so so looks like our JWT class is looking good I will shortly see this in action and it will generate us a JWT token for us let me go and add a controller in here I'm just gonna add and it's gonna call it GWT controller or CS it's gonna say controller let's make this an API controller public with a I action like a JWT I would like to get some get a gritty token right I'm gonna say return new object result I'm gonna say so here I would like to call this I would like to call this generate JWT token from so this class is declared as static and this method is declared as static so I'm gonna say jitter Beauty dot generate GWT token once a little bit T dot j WT I'm just gonna call this out that's called JWT token okay and we'll add the using statement this is inside the D helpers namespace does he help us namespace so with that thing in place let's call this HTTP GET so what so what are we doing in here we're going to call this controller this controller is the HTTP GET and this would go ahead and generate the token for us and return it back to us so playing build all looking good oops looks like I missed some semicolon somewhere yeah my bad there's a typo in there all right let's start this one without further ado and let's see the JWT token in action so I'm going to call my I'm going to so let's call this controller let me hit the break bone in here and also hit a breakpoint in here in this one okay and let's say jadibooti is called JWT okay there's the name of the controller all right so let's hit Send and it is hitting that let me go and write today let's to step through and as you can see it is using that int time for the X pi which is the box time and we have the header information as well Hydra has the header information there as well right you're saying type is JWT and the algorithm is that bit algorithm is H s 256 right H s 256 that's what we need alright that's looking good so far and we have the payload information as well so we've got and we've got this payload information so let's progress further and have generated the token for us and look at that looks like the token earth generated has been generated so let me step through while still waiting for me to complete the call alright so looks like our token was just generated all right you know what let me just copy this and go back to my this one and paste that in there and look at that our our payload information is containing all the information that we need but it looks like our signature is not valid so let's validate and see if the signature is valid or not let me minimize this on this as well and let me copy this signature go back to my signature section let me paste that bit in here I'm just going to select this and replace that and looks like the signature is verified as well now we would like to call we would like to use this token and call our endpoint and see if we can access this resource so let's see how we can access this resource with the token that was generated and now let's call this weather forecast resource so all I'm going to do is I'm just gonna copy that and get it another get because I'm just gonna say weather forecast and hit Send and we get 401 so what we are going to do this time is go to the authorization section choose bearer token and let me generate this token again because it's only set to expire it's only set to expire it has this body of one-minute degenerated JWT token so I'm going to generate this one again copy this go back and put this one in here and hit send and now we get 200 we are able to get the information back from our resource so that's how we generate the GWT token and get the resource and configure that in the authorization section I hope you like this video if you have any feedback I appreciate your comments if you did really has helped you please give me a thumbs up and share it with people who may find this video helpful and just before you go if this video has helped you in any way shape or form give me a thumbs up and subscribe
Info
Channel: the IT videos
Views: 19,643
Rating: undefined out of 5
Keywords: web api, asp.net core, .net core, web api c#, asp.net core 2.0 tutorial, asp.net core 2.1, asp.net mvc, asp.net tutorial, .net core 3, .net core mvc, .net core 3.1 tutorial, .net core 3.1 features, .net core 3.1 blazor, .net core vs .net framework, restful api tutorial, restful api, jwt, jwt authentication, jwt token, jwt tutorial, token based authentication, token based authentication in web api, programming, c#, asp.net, webdevelopment, authorization, authentication
Id: h2hGGPHLqqc
Channel Id: undefined
Length: 32min 40sec (1960 seconds)
Published: Tue Mar 03 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.