Creating a WebAPI with Authentication - A TimCo Retail Manager Video

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to another video in a tIMCO retail manager course this course focuses on real-world application development this is a series so the way the most out of it is to start at the beginning and watch through in order however if you're just interested in the topic this video covers that's fine to think this seriously a bunch of Lego bricks each is valuable on their own but seeing them put together is even more valuable in this video we say up web api with authentication we'll just do the introductory setup since we haven't planned out the application yet but we know we need certain key pieces and this is one of them now if you're a patreon supporter at the $5 per month level or higher make sure you head over to get the latest source code so let's get started let's right-click on our solution that I have open here and say add new project and select from the web category asp.net web application and notice that it is the dotnet framework version we're starting off with a dotnet framework not dotnet core because you want to simulate where businesses are today and what you'll see in the actual workplace and then we're gonna simulate the idea through actually doing it of moving to dotnet core because that's also something that you're gonna have to do in today's marketplace and so you'll have the benefit of both the where we are right now and where we're going so let's give us a name let's call it the TR M Data Manager which TR M is a timko retail manager so the timko retail manager data manager which is the API layer we'll hit OK and I also have dotnet framework let's move it up to 470 before we hit the ok so for 72 trm Data Manager is a name anthe an asp.net web application once we do we get this screen right here we get to select which version we want and I'm gonna select Web API which actually gives me MVC and Web API I'm not gonna use MVC directly in this but I will use a little bit just enough to give me some help pages and maybe some other pages too in the future but for right now I'll leave it as standard and I'm also gonna check check the individual user authentication so change the authentication to individual user accounts okay so yeah Web API these two are checked MVC and Web API I'm not gonna use docker for right now and I use Windows forms and I'm not gonna setup unit tests at this time so we hit OK and this will scaffold out for me a API it will actually run as is but I'll make some modifications to it right away whenever you add new project to a solution it's a great time to do all of your initial setup including your new get packages making sure you look at those and see if you get upgrade in this case where I have quite a few new get packages to upgrade so to get updates here we'll see that we have let's see what 15 or so yeah 15 so I'm gonna say select all and uncheck bootstrap the reason to uncheck bootstrap is because three point three point seven is a totally different animal than four point two point one so bootstrap 3 and bootstrap for there's some major breaking changes instead of trying to hassle with go to the hassle of figuring that out and fixing that for what really is a almost nothing page for NBC I'm gonna leave that alone it's gonna leave it at three the rest of them though get upgraded I'm gonna say update and it's gonna prompt me for some I believe the license they will prompt me and just hit okay to that or yes there we go there's the the updates it's got a say it's gonna do and there's the license acceptance for all the different areas they accept and it's gonna upgrade all those packages remove the old ones and put the new ones in place and to ask about this do you want replace this because it's already in place and I say yes because like yeah it's a whole lot easier because we're starting off what's the worst that could happen in this case the I believe it's the help page creates a newer version of a start CS HTML under the help page so that's that's great that's fine so hey yes it's not gonna hurt anything again because it's all boilerplate code this point so the worst thing that happens is I have to delete this project and start over not a big deal alright so let's close out this and start looking through the different settings we have here it's going to apps start and if we look here under the route config and this is where the the marriage between MVC and Web API come into play we have a route here called route config where it says controller action and ID this is for MVC which again they won't use a whole lot but it's in place in case we need it down here under Web API config is a different route and that's for the API so API slash controller slash ID and that's its routing engine or route path so if it has an API to start so your domain name slash API it's going to go to the API routing if it does not have a slash ap it's going to go to the MVC routing so that's one thing a note so if you're looking for how to tweak that that's where it's at now let's open up the identity config and in here and let's unpin this for a minute in here is where some settings are for setting up web api and it might be of interest especially when it comes to authentication for example right here is the user validator this validates if a username is acceptable or not and the default is what I'm going to keep which is no we don't allow only alphanumeric usernames because that would mean that an email address could not be a username which do I prefer and require unique email is at the true which means a user can't have more than one account under the same email address which is what I prefer again the password validator not huge fan of password ala dated the way it's set up it's not a great strong password but it is an annoying password it only requires a length of six but it requires a non numeric non alpha character meaning it has to be a special character and it requires digit and requires a lowercase and requires an uppercase so all four of these are true which means you have to have an upper case lower case number and special character and inured password but only half these six characters long I would prefer to see this longer and may turn off that one the special characters they can still have special characters even that turned off or set the set to false but that way just makes your passwords a little less restrictive again though I'll leave it at default that's fine for now in some of these things we're gonna leave them as default but maybe Larry come back and fix them or change them but I'm a firm believer in only doing what you know you need to do so if I think well down the road II might have this or might have that I might keep an eye out for those kind of things but I won't do the work for them now because half the time or more those things don't come to pass and so why spend time on something that might happen when I have plenty to do already okay so at this point let's just go ahead and start this and get it running it's gonna blow up a new version of my browser and it's gonna go to this URL which it's reserved for this application and there we go I've got my this is the MVC portion so I can go to slash API which is actually slash help is the if I click on API slash help gives me information about what's already here that basically that kind of defaults which is the values controller and also the accounts controller which is part of the authentication system now if we click on sis API slash values notice that it tells me how to call it using a git commands so git and then API slash values and what it's gonna return which is a couple of strings now if I were to call this I would say API slash values and I get this error message in XML that says authorization has been denied for this request that's because this endpoint has been secured let's see that so if we go to controllers and go to the values controller notice this red the tapas has authorized and what this says is in order for you to call of the the end points in this valued controller you happy logged in notice there's that git command right here so API slash values so that get would have returned a string array with two values in it but because we're not authorized we can't even call it so let's work at getting authorized now I have seen some people that create this method that creates an initial admin account and I admit that's really tempting to do because the fact that every time you data base for this authentication system I'm gonna have to create a new admin account but the downside of that is that then I have something in my code that has a default admin account information username password and I'm not a big fan of that and so instead of doing that I'm gonna take a little more working out my own self in order to prevent my my password getting out there a default admin account so I'm gonna create it manually every time I create a new database but here's the deal except in testing you don't create databases very often especially not brand new ones you'll do this once in production probably once and staging and in your dev environment you might do a little bit more but it's actually doubtful you'll probably do it once and then be done so I can live with that in exchange for a little bit more safety when it comes to my application and security so what we're gonna do is run this and get started I'm also going to open up a tool called postman now if you're not familiar the postman we open up a web browser here a different one go to gets postman calm and download the app postman is a tool for making API development some that sounds like something we need to do what postman does it allows us to call api's from this tool so I'm gonna call this API from this tool so let's see it's an action the first colony to make is to register a new user so let me add a post call I'm gonna start off with my HTTP localhost colon 57 306 and it may be different on your machine that port may be because it creates a new port for every new application you create so slash API slash account slash register now how I know that path well let's go back over here to our API and go the help write down here it's a post command API slash account slash register they click on it it even says here's what to send me email address password confirm password so we can do that so you come down here to this tab called body and we select raw and then over here you get a drop-down that says text right now we want JSON which is application slash JSON and now you can paste in or build in this case I'll build it our JSON string and Jace is essentially pretty easy learners put the curly braces around objects and you put square braces around arrays so that's case I have an object and the first piece is email and so I put in quotes for both the the parameter as well as this value put in quotes it's test at oops Tim at I am Tim Cory dot-com and then the password my super secret password here is PWD 1 2 3 4 5 . that has an uppercase a lowercase a number and a special character confirmed password the same password so guy post going out to API slash account slash register let's do a little bit there so there's my URL I've got in the body I have a raw selected and JSON slash applications slash JSON and then in here I have my 3 values and inside career aces there's email confer password and confirm password okay so that's the value them sending if I hit Send it comes back and let's zoom in down here and we see the status is 200 okay and if you're not familiar with HT HT ml or HTTP status codes 200 is the yes everything worked so in this case everything worked we created our username and password so now we can start using it let's actually create a new tab here I'm I just copied this the base string here and now I'm going to get what's called a token now a token what it does is when you log in through a pass a username password when you log in it gives you back this string that you can use saying I got this from you so therefore I'm off arised and it will last it depends on how you set up where I'll leave it default for now so the fault I believe is two weeks now you can make it last less than that or longer than that if you want a lot of companies what they'll do is they'll make it last for say 30 minutes but then they'll have a refresh token that will allow them to keep refreshing it so that if you continue use your application you stay logged in longer other applications will leave you logged in for long periods of time so in ours I think that staying logged in for long period of time not a big deal so we'll leave it like that so we get this we put in our path to the the base path New York to the API slash token and this is a git command now if you're not familiar with git versus post the very very basic simplest explanation is that git is asking for data and post is telling you a save this data so you may send data up with a git command and we will but the reality is what we're asking for is for data to come back the posts what we're saying is the data I'm sending you I want you to save it so that's kind of difference so here we do this post we were saying I want you to save this information and said yep we did that and you're good to go over here I'm gonna say I have some information I want you to use that to give me information back in this case I want my token so our path slash token notice there's no API there it's just our path slash token now when you send data with it so we got a body and this one we have to do X - w WM - URL encode and the reason why is because it's essentially put that at the end of the URL this is how this one call works so we come down here to our key and we type grant underscore type and the value is password the next key is username and the value is Tim add I am Tim Kory calm the next is password and the value is PWD 1 2 3 4 5 . so we have a get call to our slash token that's a URL in the body we have this form encoded and we have three values grant type username and password notice that this time it's not asking for confirm password because we're not creating this we're just saying this is my password and so it's either gonna work or it's not so let's run this and notice now I have in the body down here some information first we have the access token and the access token is that value I was talking about that basically authorizes us to say this is who we are and we've been we've been authorized now this is a bearer token and it expires in that's not really very helpful but don't worry down here we have a translation it expires on Thursday January 31st at 4:16 a.m. and the user name is Tim ads I am Tim quarry calm so that's all the information we get back so with that I can copy this whole access token now once I have this I can make a call so let's go back over to our API and go back to the the help page over here and go to z' api / values this is the one that gives problems before so now we can help up a new tab we can say HTTP localhost and most like that's gonna start but we'll take this out and say api / values this is a git command now if I just run this as is and hit Send I'm gonna get that same error now notice there's that 401 unauthorized that's the HTTP status code of unauthorized and we also get the message that says authorization has been denied for this request so we can't just call it directly because we have to be authorized well how we authorize something we go over to headers and in the headers we say the key is authorization and the value is bearer and then a space and then you paste in that token now let's make this call again and there we go so we have an array with value 1 and value to being returned because we are authorized because of this token right here so authorization bearer space paste in your token in the header you do all that and now you're authorized to get these values they'll become very important in the future we will happen for a WPF app is where login it's gonna have a store this token and then it's gonna have a send back that token as the authorization every time makes a call that is secured not only will that tell us that they're allowed to get into our application but even tell us who they are and let's actually kind of show that off a little bit and go ahead and close out this browser which will also stop the API and I'm gonna make some a couple of tweaks here so we already say we have to authorize in those values controller but what we're gonna do is I'm going to show off a couple of different things that we're going to do in this API to make it a little bit better we're gonna do is we're gonna get the user ID of whoever's logged in here just as a demonstration so the first thing I do is open the using statements we have to add a using for Microsoft dot asp net dot identity and this will help us get the extension method that we need to get the information about the user let's say string user ID equals request context dots principal dot identity dot get user ID and what this does is it says okay you've been authorized great but we could have 10,000 authorized users we need to know who you are and so we can grab the person's identity and say okay in that identity one of the things you have is a user ID please give that to me and that's me stored in our string now I can pass that back just to show that we have it oops didn't copy there you go to pass that back in my string array now if you're a little bit lost no problem just hang on just a second and I will show you where we're going with this once that starts up I'm gonna make the same call to the API slash values which is the controller we just modified now I'm still have my same bearer token but remember that lasts the next two weeks so I'm good I hit Send now I have three values and one of the values is this value right here which looks an awful lot like a GU it because it is that's my user ID how I know that well if I were to highlight this and copy it and then go back to visual studio let's go ahead hit stop it's easier go to sequel server object Explorer open up my sequel servers I have a database here called trm Data Manager sounds an awful lot like my product over here for web api this is the table that are the database that's created by entity framework for the authentication system one of the tables in here is asp net users so if i say view data there's one person in here Tim I am Tim Cory calm the password is a bunch of nonsense it's not nonsense it's a one-way encryption essentially and so it's not only helpful to us that's just just hash and there's also a security stamp but the very big game you have this ID now if you remember it for me for lets open up notepad and bring up here in just a minute this is what I got from the postman and to compare that with this they're the same so it pulled that ID off of my record and said that's who you are now I could have grabbed the email address or something else but I think this provides the most information for me because it allows me then to uniquely identify this user even if their email address changes so we're gonna use this to kind of further limit things so right now I'm just saying doesn't matter what role your Amazon I'm gonna actually even in a role we don't have any created roles we're going to get to that in a future video but right now I'm is authorized which means I can log in do whatever essentially but in the future what we'll do it'll say ok who are you and once you feel that out based upon who you're logged in as not who they say they are it's not gonna ask them where I get that off of their login information once we do then we can say ok based upon who you are this is what you have access to and that's how you tighten the net even further as to what they can see so if there are two sale representatives that can both see sales but only for their own sales we'd only have to say are you a sales representative because then we can further define it by this ID and say ok you're a sales representative but you're also Tim quarry therefore you can only see Tim Cory's sales not everybody's sales so we don't have to have a very complicated system by which we track different and permissions you only have to have a simple set of groups and then beyond that we can tighten things further by who they are and look that up based upon their user ID not from what they tell us that way it's totally secure or at least very secure nothing's ever totally secure okay so now we have that let's talk about the return types and this is a debate and it kind of depends on how you want to set things up right now the example returns the actual values so ienumerable of string or a string or a void that's the example code they gave us now if you notice when we actually call it in postman one of the things that does it returns this 200 okay which isn't anywhere in here and so what happens is if you return actual value or a void if it succeeds it's gonna say it's a 200 success if it fails because it crashes then we'll give an error and I believe it's in the 500 range and if you don't allow them to login if you say you're not authorized they get a 401 and if they can't find the controller or the the method that returns a 404 page not found so that happens by default however we can be a little bit more specific about it if instead of returning the actual type what we do is return an IH TTP action result let me show you how that work I return this instead instead of returning this new I would wrap it in okay so I return okay then inside the okay I can return the actual value the benefit there is I have a number of different options that I can send back I could send back and not found which is a 404 or an exception or unauthorized but I also choose bad requests or conflict or redirect so I have a little bit more granularity like a return the downside of it is if you scan through how do you know what get returns sure returns an IH d P action result but what's the actual data types this doesn't tell you you have to come down here and look at the actual return just through the data type is in this case it so you're gonna wrap inside and okay it's a little more obtuse I'm not a big fan of this I like the additional options for what I can send back but the reality is it makes for painful reading so it's up to you which way you want to go if you want more control over your result list then this is the way to go but you're gonna have to do a little more documentation or in some way much more clearly state what's going on because this was a stringer right right I cut this out and type tests that also works so I can change my type accidentally and there's nothing to stop me that's not really what I want so I'm not gonna do that for this API I'm gonna leave it just like that where we return the actual type like it's a method it will still wrap it in proper HTTP response codes I just don't have quite as much easy granularity on the response code sent back all right so I think about done here now I'm gonna leave this values controller in place for a little while because it's a great example of how to do things there's a couple of kind of tweaks you have a do with api's for example this is an MVC controller how I know because it inherits from controller whereas this is an API controller I know because it inherits from API controller so kind of subtle difference they look pretty much the same it's just that little bit of difference the other thing is I have now as an example of how to get a user ID therefore yeah I'm kind of good there I kind of have that baked in ready and so I'll leave it in place for a while and then once we have a few API endpoints under our belt then I'll go ahead and take it out I really don't like example code living too long in my application but at the same time I like to have an example to look at especially one that I know works so the next step we need to do is go a team Explorer and go changes and notice there's a lot of changes there's a lot of changes now normally I'd be a little more thorough in reviewing this but the reality is I just added my project I know that there's a ton of stuff I know it's all okay so I hit stage and I just do a real quick scan to make sure that no file gets added that I don't want for example the one thing I don't want in here which is not in here but the one I don't want is I don't want my packages so those aren't in here which is good there is however this whole scripts folder that has a whole bunch of JavaScript which could have gotten from npm or another package manager that's how this template is built not a big fan that's how it's built and so I'm gonna leave it alone for now I'm not gonna touch it because I also don't necessarily need all these scripts and at some point I'll come through and clean them up once I have a better handle on if I even want the MVC side of things at all I'm gonna leave it for now because not quite sure if I'm gonna have a little bit a landing page for my API just tell people okay here's the API is what it does and here you can get more information about it so Ali is for now but it's not a great solution besides that all the rest of files see me okay basing be valid files to add so now I staged them all I'm gonna do I staged them I don't if we caught that or not eyes right clicked and said stage now if they're staged I had to say on stage but remember that you take changes and move them into a stage and then commit them as a group in this case add the Web API project that's good enough I hit commit staged and go a sink I'll do my effects to make sure there's no new change in the server is not which I knew it's why I didn't do the beginning of this project but you know normal day's work especially in a team environment you'd want to do a poll first and then do your changes but in this case I already knew they had a latest version so now I can just go ahead and hit push and so now my changes are on master in github now I can't remember that I am simulating a one-man shop or one-person shop I am not simulating the idea of a team environment with team concerns so I has committed to master and I pushed to their remote master I didn't do any pull requests I didn't do any separate branching and all the rest because I'm one person so if you get into a team even two people you might want to start thinking about separate branches for your changes but in this case especially starting out I'm not gonna branch me I work right on master ok so that's it for this part of the project we have an API layer in place just basic but it's set and ready to go for our next step and gain this project setup remember we're doing a Minimum Viable Product so once we get the the main pieces in place then when I start planning out how do you want us to work and what major feature you want to work first and try and get just that feature in so that's kind of the road map a little bit we've got to put dil UPF in place which is our front end we've got to have our sequel server data tools product in place because that's where we have our sequel server for everything besides authorization and authentication and then we need to plan out that again that that one Pete's are not put in place first okay thanks for watching and as always I am Tim quarry you [Music]
Info
Channel: IAmTimCorey
Views: 172,887
Rating: 4.9368987 out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, course, training, how to, tim corey, C# course, C# training, C# tutorial, C# app start to finish, timco, timco retail manager, wpf, asp.net, .net core, asp.net mvc, autofac, c# solid, c# solid principles, dependency injection, tdd, unit testing, xunit, moq
Id: _LdiqQ13NBo
Channel Id: undefined
Length: 40min 49sec (2449 seconds)
Published: Mon Jan 21 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.