Implementing basic authentication in ASP NET Web API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this is part 18 of asp.net Web API tutorial in this video we'll discuss implementing basic authentication in asp.net Web API so here is what we want to do we're going to have these two tables users and employees if I log in with mail username then we want to authenticate that user and authorize him to retrieve only male employees from this employee's table similarly if we login with female username then we want to authenticate and authorize him to retrieve only the female employees so the first tip here is to create user's table we already have the employees table so let's flip to sequel server management studio here is a sequel script to create and populate users table with test data I'll have the script available on my blog in case you need it I've already executed this script so here we have both the tables with test data the next step is to update our ad or dotnet entity data model so let's flip to visual studio the ad or dotnet entity data model is present in employee data access project so let's double click on this employee data model at the moment we only have the employee's table here so let's right-click on the designer surface here and select update model from database so this is going to show us the users table so let's select the users table and then click finish so this should add users table to our ad or dotnet entity data model the next thing that we want to do is create a custom class that's going to check if the provided username and password are valid so let's right click on our employee service project ad and we want to add a class file let's name this class file employee security within this employee security class we are going to have a public method which is going to be static and this method is going to return boolean let's name this method login this method is going to have two parameters both of them of type string the first parameter is username and the second parameter is password now within this class we are going to make use of the entities that we have in our employee data access project so let's bring in employee data taxes namespace so within our login method let's create an instance of employee DB entities class let's call the instance entities equals new employee DB entities so here we are going to write a link statement which is going to return true or false it returns true if we have a matching username and password in the database table otherwise it's going to return false so return we have the entity's instance dot users dot na user such that user dot username dot equals so we are going to compare the user name with the provided username and we want this comparison to be case insensitive so string comparison dot ordinal ignore case so when we compare the username we are least worried about the case sensitivity and we also need to verify if the password match so user dot password equals D provided password so if both the username and password matches then this link statement is going to return true otherwise it's going to return false basic authentication is implemented as a filter so we are going to create our own custom attribute so let's right click on our employees of its project ad and we want to add a class file let's name this class file basic authentication attribute and this class is going to inherit from authorization filter attribute class and this class is present in a different namespace let's bring that namespace in system dot web dot HTTP dot filters and we're going to override a method that's present in this base class and that method is on authorization and notice this method has a parameter action context this parameter provides us access to both the request and response object now with basic authentication the client sends the credentials using a header so the request object has got headers and we check for authorization header so let's use this action context parameter we are going to use the request property to get to the request object and we are going to check for headers and the header that we are looking for is authorization header if it is now then that means the client has not sent the credentials in that case we want to send unauthorized response so let's go ahead and create a response so action context dot response equals we are going to use the action context again dot request dot create response this method is present in a different namespace so let's go ahead and bring in that namespace system dot net dot HTTP and we want to return unauthorized status code so HTTP status code and this HTTP status code Clause is present in a different namespace and that is system dotnet dot HTTP so let's bring in that namespace and we want written unauthorized so if the header is not present then we know the basic credentials are missing in that case we return unauthorized else if the header is there then we want to retrieve the username and password right so let's create a variable of type string and I'm going to call this authentication token equals again we're going to use the action context object dot request dot headers and we're going to look in the authorization header and we use the parameter property to get the authentication token okay so here the authentication token will be base 64 encoded so basically you know we are looking for a username and password and the way they will be sent is username and password will be separated by a colon like this and then this won't be a regular string it will be base64 encoded string that will be passed to the server from the client so whatever we have in this authentication token is going to be base64 encoded and it will be in this format username colon password so we need to do two things in order to get to the username and password first we need to base64 decode that and then split it using this colon and then retrieve the username and password so first let's base64 decode it to decode it from base64 we are going to use the convert class dot from base64 string and to this one we are going to pass our authentication token so once it is decoded we need to retrieve that string and to retrieve that string we are going to use the encoding class which again is present in a different name space system dot txt so let's bring in that namespace dot utf-8 dot get string so this is basically going to return the decoded string and let's store that in a variable of type string let's call this decoded authentication token okay so in this variable we have the decoded authentication token but again we still have the username and password in this format so we need to split that using this : so the next thing that we are going to do is on this decoded authentication token let's use the split method and we are going to split using the colon symbol and what is the split method going to do it's going to return a string array basically in that array we are going to have two strings the first string contain the username and the second string contains the password so let's stir it in a variable of type string array let's call this username password array so this username password array contains our username and password now let's create a variable let's call it user name equals user name password array of zero so that's going to give us the username and similarly to get to the password we use username password array of 1 so now we have our username and password now we need to do one more thing we need to set the current principle of the executing thread to this username so we know you know the username that we are using to execute the code so f now remember we have created a custom class employee security which is going to check within the database if de provided username and password match so we are going to make use of this class here so if employee security dot login and to this we are going to pass username and password so if the method returns true what does that mean we have the username and password in the database and in that case we want to set so this thread class is present in a different namespace system threading let's bring that then so we want to set the current principal of the thread to new generic principal and again this generic principal class is present in a different namespace so let's bring that namespace in that is system dot security dot principal and we are going to create a generic identity here so let's create an instance of genetic identity class and to this we are going to pass the username so and it also requires rules for now let's set rules to now so basically here we are creating a generic identity and a generic principal and setting that as the current principal for the thread so if we have a matching username and password this is what we are doing else what do we want to do if the username and password doesn't match then we want to return unauthorized response so let's do the same thing here so we have you know our basic authentication attribute now we have set the current principal of the thread to the identity of the user so now let's modify the get method within our employees controller to return you know only male employees we are logged in with mail username and only female employees if we are logged in with female username within our employees controller let's make use of the authenticated user name so with our employees controller we have our get method here so within this get method I am going to create a variable of type string let's call this username equals thread the thread class is present in system dot threading let's bring that namespace in dot current principal dot identity dot name now remember within our basic authentication attribute we are setting the current principal of the executing thread to the authenticated user name so we are retrieving that authenticated user name right here and we know this username is going to be male or female now if the user name is male then we want to retrieve only male employees and if it's female then we want to retrieve only female employees so the authorization we are going to do it here so we are going to switch on the username so if the username is male then we want to return only male employees if it is female then we want to return only female employees if it is default that is if it's not male or female then we simply want to return a bad request we don't want any message so let's get rid of this message from here so if it's not male a female we are simply going to return a bad request so here we have modified the kept method within our employees controller to return only male employees if we are logged in with male username and it's going to return only female employees if we are logged in with female username to keep things simple let's remove this require HTTPS attribute from the get method now the basic authentication attribute that we have just created this can be applied on a specific controller specific action or globally on all web api controllers to enable basic authentication across the entire web api applicate can register this basic authentication attribute as a filter using the register method in our Web API config class so just like how we have registered they require HTTP attribute in a similar way we can register the basic authentication attribute as a filter which is going to enable basic authentication across our entire web API application we can also apply the attribute on a specific controller for example if we apply it on the employees controller like how we have apply the enable course attribute then it is going to be applicable for all methods within our employees controller in our case let's just enable basic authentication for this ket method so let's decorate this with our basic authentication attribute let's save our changes and give our solution and Bill let's test basic authentication using fiddler notice here we are issuing a request to slash API slash employees this calls get method within our employees controller notice this get method is decorated with basic authentication attribute but with the request that we have issued using fiddler we have not specified any credentials so when we execute this notice we get status code four zero one unauthorized so we need to specify the credentials as well so if you look at this basic authentication attribute that we have created we are using authorization header to retrieve the username and password so with the request that we have issued in fiddler we are going to use authorization header to specify user name and password we are using basic authentication so we need to specify the string basic and then followed by that user name password string and remember username and password should be in this format username coolant password we have a username female and the password for that is female but we cannot specify the coolant separated username and password in this format we will have to base64 encode this there are many websites that help us do that if you just google with this string base64 encode the first website that you'll get is this one base64 encode dot org and in this website you can paste your username password string in this text box and then when you click this button we get the base64 encoded string so let's copy it and specify it in fiddler now let's execute this now notice we get status code 200 okay and if you look at the JSON data that we got notice we only got female employees because we have used female username now on the other hand let's try and use male username the password is also male let's click this encode button to get the encoded string let's copy this and specify it here so when we execute this we should only get male employees so if we look at the JSON data notice we only have male employees now what happens if we use an invalid username and password let's say ABC and ABC we don't have such username and password let's encode that first copy it and specify it right here so now when we execute this request we should get unauthorized so notice we get status code for 0 1 unauthorized as expected on this slide we have employee security class code and on this slide we have basic authentication attribute class code now if we navigate to localhost employees dot HTML and when we click this get all employees button notice we don't get the data that we expect and if we inspect this request in fiddler we got four zero one unauthorized now if you look at that HTML page in visual studio we are using jQuery AJAX to call the Web API servers but we are not passing the basic authentication credentials and that's the reason why we are getting four zero one on rise in our next video we'll discuss how to pass basic authentication credentials using jQuery AJAX thank you for listening and have a great day
Info
Channel: kudvenkat
Views: 351,960
Rating: 4.8395572 out of 5
Keywords: asp.net web api 2 basic authentication, web api basic authentication fiddler, asp net web api authentication and authorization, asp net web api basic authentication filter, web api basic authentication example, web api basic authentication c#, asp.net web api authentication, asp.net web api authentication tutorial, implement authentication in web api, web api 2 authentication and authorization, web api authentication and authorization example
Id: BZnmhyZzKgs
Channel Id: undefined
Length: 19min 16sec (1156 seconds)
Published: Mon Oct 03 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.