Secure a .NET Core API with Bearer Authentication

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
I've got a bunch of keys here they've been around since ancient Egypt not these particular keys but keys in general have been around a long time but why do they exist basically to protect things that you don't want other people gain access to now that theme is as true today as it was then so in today's video we're going to explore that theme and I'm going to show you how to protect your dotnet core api's [Music] well hello wherever you are when ever you are where am I Melbourne Australia as usual and when is it it's fabulous 2020 so it's my first video of 2020 and as I mentioned in the introduction we're talking about securing your dotnet core API is today as part of that discussion we'll talk about as your active directory we'll talk about being an authentication itself JSON web tokens all sorts of good stuff so stick around just before we get started just want to remind you if you like the video please give it a like it helps me out and if you want to get notified of all the new stuff and per note remember to subscribe and dignity bail and you'll get notified whenever I put on you but you out other than that I think we're ready to get started so let's cool ok so yes we're securing a dotnet core API using beta authentication and what you'll learn in this video you'll learn about beta authentication and JSON web tokens you'll learn how to use active as your active directory to secure an API and be the identity and access management layer for us you'll learn how to code and configure your API endpoints and you'll learn how to write a client a plane ticket and access our API the ingredients that you'll need for this video if you want to follow along dotnet core SDK 3.1 text editor I recommend vs code which is free and awesome and I count on Azure the features of Azrael that we're using are actually the free anyway you don't don't actually paid for features so no cost and kobir and optional postman client we're only going to use that very briefly so if you don't want to bother installing that that's ok and about 60 minutes of your time so what is our event occasion use case and then they and the top just could not interact and all I mean by that is there's going to be no human intervention by entering user IDs and passwords or anything like that we're not doing that this is an application to application examples was not interactive so let me take you through what I mean by that we're going to create a very simple API and we're just going to use the dot manure command with the Web API template and that is it will obviously add the code in the config required to secure that API but we're not doing anything more and anything more detailed with the API other than that we're going to write our console application is going to be a secure client there will allow us to get access to the API and central to all of this is going to be Azure Active Directory and as your Active Directory is going to act as our identity and access management layer and it's in the ER that we're going to register both these applications our API and our client and it's that configuration that's effectively going to allow as your Active Directory to act as that Identity and Access Management layer and allow a client to securely acquire a token and in caller ABI I think as we move through the actual examples it will be concrete up but let me just run through this scenario before we do that so what will happen the client will try in a choir talking from Azure no obviously there's a bit of config required there we can't just issue talking this to anybody you'll see how we do that when we come to that part assuming the the client is authorized to quieter talking it will get the token and then this is for a bid or authentication gets its name the the console app is ain't gonna be the beta of this token by issuing an HTTP GET request to our API and B of the token towards it and assuming the talk in is valid and again the API will check with as your to make sure that's valid it will return back an HT t HTTP response with our pay Lord or not it may go no you're not authorized to do so so that's the that's basically the use case that we're going to go through just a couple of points just before we move on both the API and the client are just going to remain on my desktop app I'm gonna stop on my desktop I'm not going to deploy the API to zero they're just going to remain local but we're still going to use these your Active Directory as as the identity and access management Leo so that's one point you can obviously put the API up to zero or Amazon Web Services or anybody else you like and so long as that platform can contact us your you can still follow this pattern another thing was I was originally when I thought about this video the original idea was to write code to start issuing tokens and entering passwords to get a talking and I thought why do that we've already got Azure Active Directory they are it's a it's an industry commercial-grade identity and access management they are applying the earth when I attempt to write my won-won I want to just focus on the value of my API the unique cool stuff about my API without reinventing the field when it comes to a tenth occasion so that's why I've done that in this model I think it's much more applicable in the real world then I'm not talking I think we better get started coding okay so let's get started with our first build step which is to build our base and pull API so I'll just open visual studio code and I'll move into my working directory which is on my D Drive and I'll change into s3 which is season 3 and I'll change into episode 1 which is this video and there was nothing in there and then all will simply do is the dotnet new and that'll give us a list of template applications that we could pick from and as I mentioned we're just going to pick this Web API one so aapki wave api and we'll give it a name we'll call it secure secure API hit enter and that will go away in scaffold up the very very simple API project for us so just doing a directory listing you can see it's they are and now if you're using BS cord you can then just take cord - are and in the name of the folder and that will recursively open our project in Visual Studio code which is pretty cool now just another quick tip if you hold down the ctrl key even the apostrophe that will open up a terminal and to get to terminal Flores in the right folder and you may get you will almost certainly get this pop-up here just click yes to that and that just basically goes away and make sure that our project has all the resources it means so we're not going to do much with this API the main thing we're going to be working and we're going to be working in our startup class and again I have another video that takes you through the detail of what this does and will will update this as we go through the video startup class no surprises are basically where we set up things we set up from requests pipeline and we set up our called services within our application but let me cover that when we come on to that point so we're going to work in a startup class a bit and also then our control our class so a controller is basically for our API endpoint methods will sit and as you can see in here we only have one HTTP GET method which is basically returning back this list of weather conditions so let's just test that it works and make sure we've got no issue they are again I'm not going to do too much with this other than what's they are so dotnet run and you'll see that it starts up and it's listening on to two addresses HTTP port five or one five zero zero one or regular HTTP on port 5000 so we just want to test that we can access this API so I'm going to use postman for that and as you can see I actually already have the correct URL in there so it's just what appeared down here you go so that's just what we put and I'll address the veil reuses get and if we click send we will look at our response when we get our 200 or k response and we get some JSON output telling us what the way that was going to be like not really interesting than that but the point to note here is it's not secure we can go in straightaway access it no problem so it's this endpoint this yeah this API endpoint to secure with beta authentication so Nick makes few steps in our video and our tutorial is using Azure to configure up our API client that have just maybe I like camping up the API them have just created so I'm just going to pop into my Azure portal so when you go into your azure portal you will just click on active directory and we have a number of options about things we can do and the first thing we want to do is go into a preju stations and this is where we're going to we're just on both our clients which we will come on to later and now we're going to register our API within as you are so we'll go a new registration so we just give it a name I'm going to call it where that API and I'll then I'll just say it's an a development environment because we may not in this video but you may have different environments that you want to have different registrations for we will leave this checked accounts in this organization organizational directory only and we don't need a redirect URI so we'll just click register there now will go away in register our API in as you know our API is sitting down on our local desktop and just done this registration as you are at the moment that just completely disconnected entities we've treated this rather abstract concept of a registration as we go through the video you'll see how that starts to tie together and the API will actually go to Azure and go I'm here but we've not done that yet so at the moment you're maybe going well that's just completely what is this it will become clear as we move through the important thing to look at here as we get this is a wrap this is our weather API registration information page and we have a number of bits of information that we're going to need to make use of later so the first one is this application or client ID and it's just a good a directory or tenant ID now that's actually the ID of this active directory which will remain the same for all registrations in this directory whereas the client ID will obviously change for each registration it will be unique to that registration so we don't need to do anything else with that information that moment just be aware that it is there the next thing we want to do within this registration is create what we call an application ID URI or as I'm going to refer to a resource ID so in order to do that what we do here is we go to expose an API which is basically our API registration if we want to kind of expose to the way the world and all we simply do is click on this little set button up here now what as you will do as a default it will provide this API call on forward slash forward slash and this is just the client ID or the application ID that it created and we just click Save is that simple so basically telling as your that yeah this is an API and we want to kind of court on court expose it for use and you'll see how that plays out a bit later on so if we go back to our overview page what you will now see is in this application ID URI we have now this application ID URI or as I'm going to call it a resource ID again we'll use it later and then the last thing we want to do in terms of configuring our API and as your is update what we call the manifest so again within our weather API development registration we click on manifest and it's basically just a JSON file no what we actually want to update is this attribute here now what is this basically all we're telling the telling as you as the type of applications that are allowed to access this particular API and and in our instance we want to allow a daemon client to connect and and you can have multiple different applications that are allowed to access no it's just a big bunch of Jason I am not going to take I usually like to take although and I'll take called oh this is just in my mind config and I'm just going to well I'm just going to cut and paste it from the blog article that we have on the subject so just to split my blog a little bit dotnet playbook we have an article on this with all the steps I'm going through here and I have very kindly and provided the JSON that you will need to paste into the manifest file so again what our stop dating app roles and we're talking about the type of application that we are loving to access our API the important thing that I would destroy it attention to if you're adding multiple application types you'll want to have a unique ID for each but we're only adding one so I'm just going to copy that Jason again I don't usually like copying stuff but it's such so prone to error that I'm gonna do it this way so please forgive me in this instance so we'll delete that and then we'll just paste in and you can see it's slightly miss formatted that doesn't matter let's click Save and all be well it should have successfully updated if we just come back out and go back in you'll see it's reformatted the Jason and you know a nice and there's a nice indentation there's no errors it all looks good so basically all we're saying is the type of application rules that are allowed to access a this API in this instance is a demon app rule okay so now we've got to move back over to our API and actually make some changes to it so that the this rather abstract a config we've just created in the sewer and our API that's still sitting on our local development environment can it come together and that's what we're going to do now now the first step of that is actually providing some configuration values to an API that we have in Azure that we have in our as your app registration so if we come back over here you can see we had things of the client ID the ten ID and the results ID so we're going to actually provide some of those values as configuration elements to an API so it has access to the minute can then use them to talk to as you angle by the way I'm here just before we do that one thing I would suggest if you're doing and this is obviously a learning environment at your toriel environment and I've put all this code up want to get hub for you so you can just download it and you can just update the app setting jayson's file with your individual values makes it nice and easy for you if you've got doing this anymore productionize environment I would suggest not using app settings Jason or these values but using something that user secrets if you are just running in a develop your local development environment and then once you actually finally deploy it then if you're deploying to 0 for example using something like key vault or just the configuration layer for your API and as you are I wouldn't store it in app settings Jason because the data is quite sensitive but as this is a tutorial and for the interests of brevity and time I'm just putting it in there so what we're going to do is we're going to come back over to our API and we're going to go into app settings Jason and we're going to I'm going to type this so we're going to add some new Jason so we're going to add a top-level key will just call it LED as your active directory and then we're going to add a range of values into that for the config elements that we need now the first one we want is resource ID and we'll go back over to jour and copy to clipboard to come back down to 0 make sure to put it in double ports and paste that and that's a resource ID and then we are going to have an instance into this ID now the instance ID is actually I'm just going to copy this from my blog article actually show you that I'm sake and then we're taping it and here's the blog article on exactly what I'm going through here well I've got one screen that higher resolution than my safe can do scheme that's why it's acting a bit strange but anyway I've got this JSON here that you'll need to update your app settings Jason with these are values that are unique to me obviously you'll need to update them but they are here anyway come back to the instance ID it's really just a sort of login ID for as you that's all it's a standard URL that you will use as you use the same one as me the source ID and ten an ID officer it would be different so let me just move that back over here don't forget good comma in and then as you saw there the last one is ten ID and if you remember tenon ID is just the I unique identifier for your is your Active Directory instance and double quotes and I'll need to go back over here and get a tenant ID and just copy to clipboard and paste in here cool so we'll save that and all that means is when we start up our API in fact that's just running a moment I'll just stop it when we start up our API these values will be a made available to our API as part of our configuration system through this configuration object yeah and you'll see how we use that in a bit okay so we've added our Azure Active Directory configuration elements to app settings config call what we need to know know do is make use of those configuration elements from within our API and affecting what it's doing is we're going to add a thent occation service to our api we're going to configure that authentication service using those attributes so before we do any code changes we need to add a package and your package to our api app i've opened up our project file you can see it's relatively empty so we just do dotnet and package Microsoft this is fair and I loved intellisense ESP net for authentication and I've got type of authentication do we want to add well this is the money shot JWT data authentication so it just adds that library for us assuming I've taped it correctly I think I've taken correctly Microsoft ASP net core often same then the katechon okay missing a name let's try that again here we go okay so we add this package reference into a project file let's just do a dotnet build make sure that's all okay cool it's so we move on to a startup class now in the first thing we want to do is make use of that package we just added so Microsoft thankfully that is a tail until a census time authentication and the GWT beta go again the video I done I've done a number of videos on API is now that goes into detail about what configure services method is responsible for and configure is responsible for not going to dwell on that too much you as the name suggests configure services allows you to set up a number of services that can be shared during the application and configure just sets up your request pipeline I'm going to leave it at that for now but again if you want more information on that check out my other videos so we want to add the authenticate the authentication service to our API and we're going to use GWT beta authentication as the flavor of authentication so in order to do that we add something to our services collection and authentication and then here we configure more detail so we're going to use JWT bailer defaults authentication scheme and then i'm just going to start a new line because we're running a space of e bit and we're going to add a beta as it says they'll add GWT bit off and they just gonna they in that state this is where we provide our options into this to basically configure up JWT beta authentication so we use about my lambda expression opt goes to and then we'll open our curly brackets let's put call on at the end here just to close that and we'll start configuring the options that we want it so the first one we want is audience so as far as Active Directory is concerned who is the audience for this and in this case it's us me the API so we're going to provide you figure out the authority excuse me the audience there we go and who is the audience well it's basically the resource ID of the API but we're just saying I'm the audience and here by the way here's my resource ID and maybe access our resource ID is through app settings Jason just to remind you we have this top-level key aad and in a sub key of resource ID so we're going to access that via our configuration object configuration square brackets and then we just access that by typing in the top-level key call on and then the second level key which is resource ID now I might just pop over here and just copy this one because this is where you're likely to make typos mistakes and they are the kind of things that will drive you crazy when the thing doesn't work I think that was right anyway okay so that's our audience who's the audience the API cool losing my voice here and then the next thing we want to do is set up who's the authority who's the authority to issue web tokens on our behalf any guesses that's right this is your Active Directory but we need to tailor which one so opt Authority and this is a little bit long-winded but we're going to use the string dollar syntax to use a couple of configuration methods a couple of configuration elements sorry so curly brackets corn figuration square brackets a ad call on and the first thing we want to pass in there's a instance ID so excuse me for copying and pasting by again this is the kind of infuriating stuff that will go wrong and you know it just drives you mad so close off the square bracket close off the curly bracket cool and we're going to add one more piece of configuration to upon the duration and open square brackets start double quotes aad pull on and then the last thing we want to provide yes is of course obtain an ID so basically all this is doing saying who's the authority were providing the instance ID which is generic and Emeric pending or and effectively the tenant ID which is the unique ID of our active directory I'm not copying the actual little string just copying the the key so let's go back over here and paste that in cool close off the string cuddly back it is closed off and anything I'm going to do is close off the string like that know there's something yeah that is correct cool so we'll save that we'll find out later if it's wrong I'll have to go back and revisit it and the only other thing we want to do is come down to our configure method and add authentication to our request pipeline so it's just add authentication that's it so when requests commenter's we're actually using then the learn authentication that we have configured up here with our config elements no the last thing we want to do in our API in terms of coding is let me just say that I found offensive that is to come or to or controller now this is super simple all that we need to do here all we need to do is actually decorate our endpoint May with an attribute and that attribute is actually I have to add a using reference up here first of all so using Microsoft asp net core authorization actually I'll show you every trick let me let me take that out let me get rid of that and let me type in the absolute that we need to offer eyes off or and I have to use American spelling there you can see here it's not resolving because we don't have the namespace if you place your cursor in there and hold down control and period you'll actually see it provides you a list of quick fixes and we just hit enter and it will add the it will add this using statement and for us and resolve the authorized attribute which is very cool so I thought show me that little trick hit save that's it so basically seeing an order to access this endpoint you need to be authorized to do so now this is a bit of a drumroll really the magic happens let's do a dotnet no I'm here thanks to a dotnet build down here make sure it's all building okay it is a key dotnet run looks okay and then if we go back to our postman if we click send again it's exactly the same URL that's good we get we know get a 401 unauthorized status callback which is basically seeing you're not authorized to access that's an endpoint cool a quick look at the headers and you'll see that the authentication type that's required is bail authentication so looks like looks like anyway that that part of it is working though all we need to do now is really a client that will actually go sirs you're get talking and a thing to get through to an API so let's do that next all right so though we turn our attention to the client side of things and the first thing we're going to do is create another application registration in Israel for a client so let's do that so back over and as your this is the previous application registration that we had so we're going to go back up a level and just as an FYI here are all the other application registrations I have and here's the newest one that we've just added so as before new registration and we'll give it a name and let's see where the client underscore development and as before first options fine and real click register and as before you'll get things like a client ID the tenant ID should be exactly the same as for our API that's because it's sitting in the same tenant now this is real the configuration diagram just slightly from where the API for what we did in the API if I just take you back to this slide on our PowerPoint the first step that the client application is going to have to perform is to acquire a talking from Azure now your first question is going to be relative Y with is your give a talk into this client what what is it that makes it unique Y applies are authorized to get a client no this is the mix bit of config that we need to do now in a more I'll say traditional that's maybe not the right one but in an interactive type scenario this is Rio you would put in your username and password what I'm going to use that here so what we're going to do instead within our client application registration we're going to create something called a client secret so over an hour registration scheming will click certificates and secrets and this is where you could set up supplier supplies certificates we're not going to use a certificate here we're going to use something called a client secret and the client will supply the secret to as your to go and actually who you think I am and all then provide the client they're talking so it's a really critical key piece of information and you need to treat it with the respect that it deserves so you simply click creating your client secret call it anything a label just call it a where's our client secret and we'll put underscore development follow the same naming convention and you can see here you can see an expiry on it 1 2 or never one years fine and we'll click Add and zoom goes away in case it creates this client secret for us above a tongue-twister really really really important thing here make sure you copy the secret and keep it safe somewhere I'll just open up a notepad and put it in there just now now let me just bring that over here so you can see it and I'll just save that to my desktop for the moment and just call it that's the onedrive desktop over here call it client secret now the reason I'm seeing to do that is because while this client secret will stick around and stay around after a certain time I'm not exactly sure what time limit is your puts on it will eventually redact this value so that you can no longer see it is that secure watch they'd still be there but it will redact the value and you won't be able to copy it you won't be able to go in and get it it's also a 1:1 tightened deal where you've got a certain window to copy it and use it elsewhere and that's just a security feature the Vizio which is really cool so what come on to use that later again we're going to actually use that client secret in a app settings JSON file in our app client and a client app which you absolutely would not do because it's completely unsafe but for the purposes of this tutorial we're going to use that method enemy I would use something like a Klein user secret or something than that or bouzouki vault to store it if you were doing that in a production environment so the last thing from is your perspective we need to do for our client registration is tailored for permissions it has to our API ok so in order to do that we click on API permissions and we want to add a permission to our client app to our with our API so click on add permission and you can see here you get a some Microsoft API available API is in my organization or just my API so click on my api's and these are all the api's that i have registered and you can see here this one is very familiar where the API development so we click on that we see we want to give this client registration access to this particular API now you've got delegated permissions or application permissions so as you can see here this as your application runs as a background service or demon without a signed in user take that's what we want and the permission we want to give our climb app is this demon app roll click add permission now interestingly you can see he has added it you guys added this permission but it's sing with not yet granted this permission so you got to click on this button here grant admin consent from Babel if this all witches this directory you get a pop-up click yes and you can see here that our weather API development API as being we've got this demon app roll permission to use it so as I kind of multi stage process we had to register our client app in Israel we have to generate a user secret level use later when it connects through and then we had to give up permissions to use that API so kind of multi-layered approach that makes it really quite secure so with that final step and as your thing that's everything we need to do no need to ton or attention basically to the last bit the tutorial which is coding up applying the application okay so we're going to create our client application now and that was actually a surprising amount of code involved in this which supplies me when I was creating this tutorial much more than that is in the the the API which admittedly is just a fairly basic code the Box API so quite a lot of code to go through and quite a few steps to go through but let's as always go through it step by step the other thing I'll just mention is like I have been using postman as my client of choice and I've done a bit of research you could theoretically use postman to call our API but it's actually quite not animate the third information I could find it's quite convoluted to get it to work and I think anyway it's probably better that you know how to call up a client that can use this at the inter kitchen anyway so that's why we're not using postman for this but it's very cumbersome and it's probably better that you write the cord enemy so we already have a visual studio cord session running for our API we're going to open a new Visual Studio code bundle for our line app so let's open that up as sue and then I'll just fullscreen it and control apostrophe to open up the terminal window I'll switch into my working directory change into season three change into episode one and you'll see there's our secure API project so we simply want to do a dotnet new console app and give it a name we'll call it call it secure client give me an evening convention consistent so there's going to be a secure client app call we do a directory listing you can see it's created our project directory for us and as before we can take chord - our and the name of the folder to recursively open project folders now it's a very very simple project we've got a project file you can see here and we've got our program file again very very simple OOP not control escape and build our assets control apostrophe to open a terminal window and we'll just do dotnet well if this doesn't work then I think we all should go home it's a fairly simple probably the simplest app you're going to get so that all looks good so the first thing I actually want to do is create an app settings JSON file in our project we're going to put again put some of those as your active directory configuration elements into again one of them is going to be this client secret which I again have to really be enforced do not do this in a production type environment for the purposes of what you're toriel it's fine I would use something that can use your secret going forward which I have covered off in other videos how to do user secrets so in Visual Studio code you can use this little new file button here and most call apps it Jason you can actually call that anything you like as long as it's a JSON file but let's just keep it consistent and call the app settings Jason and into app settings Jason we're going to configure a few elements within it so I'll just top-level elements so open up curly brackets the first one is going to be instance and again this should be familiar from before and I'm just going to you will excuse me copy this in that is a slight difference the instance string I'm using here you can see I'm using this construct with the curly brackets so we're going to inject the tenant ID and the earth when we contact according up the next one is in fact the tenant ID and I will go back to my application registration go back to the overview and pull out the tenant ID copy it to clipboard and pop it in here remembering to put commas at the end the next one is going to be our client ID again this will be unique for our client copy it to clipboard paste I'm definitely not going to take please goods out and be joking if I yeah I'm just going to try and do that next one that's going to be our client secret now again this one is possibly one of the most sense to the bits of information that you typically would not store and plain text like this but again I've given you enough warnings and we'll taste that in there it's actually just just of interest let's go back over to our client registration and I'll click on this again and you can actually see what I was talking about there here's our client secret you can see it's somewhat redacted and we can't copy it anymore so that's it's kind of our security feature that basically stops it being distributed at home with ease so that's what I meant by redacted it's still there it's still valid but we just can't see what it is we'd have to delete it and create a new one if that was the case so there's a client secret but then I'm going to just tell it what API base address we want to call so we'll just call that base address and that's really just this from postman copy that own a piece thing you know cool and then finally our resource ID and it's the resource ID of our API app so we're currently looking at the registration of a client if we go back up and go back into the API development API registration and we want this application URI or resource ID as I called it and let's paste that in yeah and on the other thing you need to do here is just default / default to make that work possibly what - the photo budget I would just be on the safe side and keep it there any of you so again if anything is going to go wrong it's going to be because I've misspelled these but we'll double check it when we come to actually using these attributes in our cord so let's move on to the next part okay so over an hour I've stopped and up our project file just to show you there's nothing in there at the moment and the main reason I'm doing that is because we need to add some packages to support the cord that we're going to write in the next few steps those two main parts this what the first part that we'll do after we've added the package references is to write a class that will be then the conflict we just created and then the second bit is basically to write a method in our in our main in our program class domain function to basically connect and to an API you can call it but first things first let's add the packages that we need so dotnet ad package and first of all we need is Microsoft dots extensions dot configuration so there should be no surprises there because we're wanting to create this config class there we go and then bind up and you can see here but it's adding a package reference to our project file as we call and then the next one is Jason vacation Jason and these are just supporting this class I'm about to write that what we didn't say things Jason settings and then the one we need for our authentication and authorization stuff is Microsoft identity why well come on and use that in a bit to know if obviously spelt something wrong Microsoft identity hmm no I've just typed it in okay for those of you who spotted by did their ten points and I call star been a long day there you go with dr. had package and we have to put that in much better okay cool let's just do a dot now build fantastic okay so we're now going to create our off configure class which basically is relatively simple class it's just going to allow us to read in our app settings JSON file and make use of those attributes via an object colin start up a class construct so back over in our visual studio chord session let's just click on new file call it off config dot c s or we know it's a c-sharp file cool let's just copy the namespace from program file and then we'll use class to populate the class name and call it off come on fig cool and then make it let's make it public now essentially all this classes is really just a list of properties class properties and then a little routine at the end that just reads in the file so a little bit boring i'm going to type it out as we go and you're just gonna should i should i speed-up no let me let me explain as I go on us this time and then maybe the rest of the quarter might just put some music orbit while they're taping so we need a few using directives using system using system I all because we're going to be reading from a file using the system globalization just so we're getting our reading incorrectly and using Microsoft extensions configuration cool so we're just going to represent a number of config properties contents as properties within our class so if you take prop tab it and it'll give you that outline of a property first one's going to be a string tab again and we'll call it instance so rather than watching me but you're gonna have to watch me type it rather than me go through it in great boring detail I'm going to put some music over the snow and I will then stop it when I come to something a bit more novel so cue music [Music] [Music] [Applause] [Music] Dave let's stop the music there for a bit so we've created a number of properties now what we're going to do is we're going to bind these properties to the config elements here so they need to be exactly the same so hopefully I've not made any type of graphical mistakes we'll find out if I have in a bit hopefully not just looking at that that all looks ok so let's come back over to our oath config class and and then the last thing we want to do basically is read in our file from you don't offline so cue music again and I'll come back and explain what the coolants doing in a bit but I finished [Music] [Music] [Music] [Music] okay so hopefully as a type that in that should make some degree of sense for you were creating a configuration object or basically then using a configuration builder to read in the contents of our app settings JSON file we do that by getting the current directory and when we call this method will just pass in the name of the file we want to read in and then we basically just read it in and the elements in our contacts a thinks JSON file should bind automatically to the properties that we've got in our class so let's let's test that now to see if that is working so what we'll do is we'll pop over to our program class and we'll get rid of this and what you will do is we'll create an art config instance we call it config and we will see our config read from file the JSON from file and then we'll just pass in the name of our file so at anything we've got Jason and then we'll do a console.writeline and then let's write out the name of this attribute here's a slightly more complex but can ican cat and eating two values together so dollar authority and you'll see config authority and hopefully actually have a double for now don't need that now let me go and done so save that button there build and then donate run cool so you can see his return back the authority which is basically our instance ID I believe and the tenant ID so that looks good I mean unless I made a typographical error or somewhere else that should all be working correctly so now we're moving on to the more interesting part which is actually no authenticating through a tour API okay so staying in our program class we're going to add some cord we're going to do this in two bit so the first bit we're going to if you go back to our wonderful power point diagram we're going to basically split this next cording section into two parts the first bit is going to be the acquisition of the token so we're going to do that next and then the second and final part is going to be the making the HTTP GET request with the talking to the ton of payload so we're going to break it down like that so let's go on with the token acquisition so the first thing we need to do is add a few more surprises a few using statements or using system threading tasks because we're going to do a little bit of a synchronicity asynchronous program so we need that in there and we're going to do using Microsoft identity client which is one of the packages you'll remember that we added now we're going to create a method in here called run async which is basically going to contain all our code to do those two things but we're going to tackle games talking first now there's quite a lot of code here so and as you've seen them quite a painful typist so I'm going to take the cord out put some music over the top which people seem to quite like and then I'll bring a finish typing it out I'll speed it up a bit as well and I'll come back and I'll explain what it's doing and then we'll run it and test it okay so cue the music [Music] [Music] [Music] [Music] [Music] [Music] [Music] okay so hopefully as I was typing that you can have got a feel for what was happening but let me thoroughly take you take you through the cord anyway so I'll jump straight down to this one async method here's the first thing that is novel which is this I Continental Client application so we're just creating an instance of that which is basically what we are a confidential client applications were creating that then we're going to build the config that that application needs effectively and we use this a application builder object and we just basically pass in config elements that we have so client ID the client secret Authority and then we just call a build action on it and it's this app that we then use to work within the rest of the code we have if we have more than one resource ID in this case we only have one but you may have more than one does or sidee that you want you that's why i've just created an array of resource IDs but didn't really need to do that but it's just sort of future proofing it a little bit and then we create this authentication result which contains no surprises our result and then really finally we use our app object and we here we use this method acquired talking for client and we pass in our range of resource IDs and we execute it and in a synchronous way and that's why we have the await keyboard here and that's why this method is an async method and then up in our main method we just call run a sync and any users get a waiter and get result methods and that's just ensuring that we we wait for the result to return before we go on and do anything else was just basically waiting for us to get something back the rest of the method is relatively simple and the oldest joong-ki is basically just changing the foreground color to green and writing out the talkin if we have it otherwise we have we write out an error now this is the the moment I always hate because I've genuinely type listen by hand and I want to see where they'll be configured everything correctly there's a few things that had to do so fingers crossed so let's do a dotnet build not in here there you go as a first mistake access token there we go make sure that's correct yeah okay don't heal dotnet build I don't how many things I've done that building okay so we should see back-talking let's see what happens and indeed we do we get a success which is which is good so this is basically we making the call we've acquired the talking from Azure bypassing over of config elements you need all of them but the client secret was one of the key ones there and it's returned back this kind of imported looking a Jason way of talking or doesn't look at Jason they aren't that that's what it is cool so going back to our diagram we have basically performed this four step we have got our access talking though now for a final that recording we are going to make a HTTP GET request to our API and hopefully we'll get the peel order tons so we'll do that now so yeah back over and I don't know if you can hear that it's actually raining it's just started really really heavily here and I'm not sure I'm not really used to it but in the UK where I come from most roofs are made of slate so you can still hear rain on slate roof but it's a damp and done here in Australia that there seems to be you get slate roofs or concrete type tiled roofs but my house at the moments got a metal roof and so it can get really noisy and when it rains I'm really hot as well anyway so apologies for the noise there's not much I can do about the vein in the background but bear with it hopefully you can still hear me okay so back over and our program class we're just going to start to paint some chord where we left off to basically me a request to our API now again there's quite a lot courtier so again I'm going to type it all in step by step I'm not going to paste it in put some music over the top speed it up and I'll come back and I will explain how the code is working and then final step will be to run it and see if it works [Music] [Music] [Music] [Applause] [Music] [Music] [Music] [Music] [Music] [Music] okay so quite a lot called there again if you watched me type of out most of the I'm hoping made kind of sense to you we created the HTTP client we added default request headers we just checked here to make sure that we're passing over the right I guess media type which is application Jason within then this is the important one this is kind of why I highlighted that in the chord we're going to set authoring to beta and we're going to pass over the access talking that we got in the previous step so that is a really important part of this chord adding that authorization to the headers of our HTTP client and then we basically use HTTP client to call our base address asynchronously and again our base address is just the address of our API and they read n interrogate that response mation response message to see if it's successful and if so we basically just print out the JSON payloads of our API otherwise we retrieve the details of what what went wrong that is basically it now I just want to make sure before I run it that we go back over here our API is still running I'm gonna call it in postman and you should still get the unauthorized so still trying to do it still can't do it it's alive and well moving back over to our client app gonna do a build to make sure those no syntax errors so dotnet build cool and then finally we're going to do a dotnet run so it should still go away and get the token cool and then it should depend that talking to HTTP client and we should get a payload back so fingers crossed one more time let's see what happens and as if by magic it's almost like I planned that you can see there was a kind of multi-step process there where we got our talking and there was a slight delay and are waiting for their synchronous message to come back and indeed we have our Jason pay Lord so we have successfully and fulfilled our use case well that brings us to the end of yet another video there's something tremendously satisfying for me finishing a video but also something quite sad about it as well but I won't get too sad because I'll be making lots more videos this year in 2020 all that remains to be said is absolutely once again thank you for joining me I hope you enjoyed the video if you get any comments or questions please put them below and if you liked the video you know throw me a like I'd really appreciate that until next time go I'll see you around stay safe stay happy and take you
Info
Channel: Les Jackson
Views: 125,252
Rating: undefined out of 5
Keywords: dotnet playbook, azure, azure active directory, aad, .net, .net core, api, .net core api, secure, authentication, json web token, jwt, bearer, c#, les jackson, step by step, tutorial
Id: 3PyUjOmuFic
Channel Id: undefined
Length: 66min 56sec (4016 seconds)
Published: Tue Feb 25 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.