Part 1 : Token based authentication using ASP.NET Web API 2

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello friends welcome to dotnet awesome dot-com in one of my previous article I have shown you how to implement custom forms authentication in a spirited MVC for application today I am going to show you how to secure a spirited web api using token-based authentication yes we don't need web appear is a framework that makes it easy to build HTTP services that reach a broad range of clients including browsers mobile devices and traditional desktop application now it is Web API adoption is increasing at a rapid pace so it is very essential to implement security for all type of client application trying to access data from Web API services nowadays the most preferred approach to secure server resources by authenticating users in web api is to use sign token which contains enough data to identify a particular user this is called token based approach token based approach is the most paper'd as because of this following reason it's loosely coupling the client application is not tied to a particular authentication schema the token is generated validated and ferb perform the authentication by the server second is mobile friendly in native platform like iOS Android Windows 8 etc handling cookies are not an easy task token based approach simplifies this a lot now the question is how token-based authentication actually works in the token based approach client application first send a request to authentication server endpoint with appropriate credentials now if the username and password is found correct then the authentication server send a token to as a response this token contains enough data to identify a particular user and an expiry time the client application then use the token to access the restricted resources in next requests till the token is valid okay let's start implementing token-based authentication in Web API first of all we will create an empty project so first please open your visual studio Here I am using Visual Studio 2013 okay fork it and project go to file menu then click new and then click on project you can see your a dialog window appear from here I will select a speed or need web application under wave then you enter your application name then select your project location is it okay and then click on OK button it will brings up a new dialog window for select template here I will select empty template so select empty template and then I will add MVC and wave API Co references so I check this too and then click on OK button our application is created you can see here in the solution Explorer our application is created now for implement token-based authentication in wave api we need to install some resources from nougat packages into our application and so go to your reference folder from solution Explorer right-click on the references manage nougat packages from here I'll search for Oh in I will install this one Microsoft dot weighing dot host dot system wave so I need this one can see here the require dependencies is also installed with this you can see here the wean system wave and Microsoft dot win Stein and it installed this also Microsoft dot Wayne dots equity dot over so click on install button it will also install required dependences for this you can see here this is install Mike sub dot Wayne dot security and one more thing I need to install this one this is required for cross-origin resource sharing it's done so all the required resources we have installed in our project now we will add a class in our application for validate the credential for users and generate token for adding the class go to your solution Explorer right click on your application aim then go to add and then click new item from here I'll select class enter your class name my authorization provider and then click on Add button so you can see here our class is created my class name is my authorization server provider here I will innate one class ortho authorization server provider in this class I will override to method from ortho authorization server provider class one is validate client authentication and second one is grant resource owner brilliant CL so public overwrite all right validate client authentication I don't need this one changes to sync and here our to one single large context dot validated this single line means that I have validated the client you can see here I have override validate client authentication method from Earth authorization server provider this method is used for valued client application for the sake of simplicity we will deep dive on validate client authentication method later I have just written one line here now is context dot valuated this line is mean means I evaluated the client so the second method is grant resource owner credential we will override so public override grant resource on cadencia this one this I'll make it awesome okay in this method we will validate the credential of users and if we found valid currency L we will generate the sign token using which user can access authorized resources of server first of all I will declare a variable identity sequel to names identity context authentication type and then we will valuate the client KHL here so if context dot username equals to admin and context password to Adam if it is then I will add some claims identity dot add plane dives we can add in this way as well one more I will add for showing the full name M times dot name so if username and password is admin admin then this will happen one more I will create for now what aced context Con Ed start first with testicles to using I will do the same thing I am doing this just for showing you at the testing time everything is perfect otherwise I will return error so sit later [Music] and to add this one sorry context dot validated identity I have to add this line to here also you can see here for now I am using static data for validate user here for make the application simple later part of this series I will validate user from database when we will implement client application in angular JS for token-based authentication this is done now now we will add you in start-up class where we will configure the author authorization server for adding wing start up class go to your solution Explorer right click on your project name go to add then add item from you here search for Wien start up + select this one I'll renew it start up dot CS and then click on Add button our wind startup class is created now we will configure author authorization server here first of all I will enable cross origin for enabling cross origin request I need to add this line app dot use cross use Microsoft dot dot ah start corruption start Allah all so this line is for enabling cross-origin requests now we will configure the ortho authorization server here first of all I will get a reference of my provider to knew my relation server provider this one and then then we will define authorization server options so authorization to write radiation server options as this is a demo project so I need to allow and secure HTTP in the live version we should make it HTTP form HTTP version for secured now the token endpoint path give this token sorry it should new stream this is the path from where user will get the token after providing the valid credential now I need to access token expiry turn span to provide the time free owed the access token remains valid after it was generated so it's from from days one I make it for one day valid after generate to define the fovea my provider or to authorization server options then I need to tell the application to use ortho authorization server and this one one more line we need to add when you add token options and finally we need to register wave API config HTTP pick dot mister config so this is done now we need to add a class for override authorized attribute when building an HTTP REST API you should use appropriate HTTP response codes to indicate the status of a response I always use 4 0 1 & 4 0 3 status code forget authentication and authorization status for 0 1 means unauthenticated it's indicates that the request has not been applied because it lacks valid authentication credential for the target resource and 4 0 3 for Vidan when the user is authenticated but it's not authorized to perform the requested operation on the given response we should use 4 0 3 to identify that request is forbidden unfortunately the wave api MVC web api authorized attribute does not behave that way it always emits 4 0 1 in both case for authenticate author user or authorized user so here in our wave API application I am going to add a class for override this behavior where we will return 4 0 3 when the user is authenticated but not authorized to perform the requested operation for adding the class just go to your solution Explorer right click on your project name then go add and you can choose class from here also or from here also add new item so here I will rename it is active and then click on Add button so it's added now I will inherit authorized attribute system dot dot wave dot t-- t-- p dot authorize attribute here i will overwrite handle unauthorized request so public right and then unauthorized request but will do here if the request is authenticated but or not authorized then we will return for region from here so if HTTP context dot current dot user that identity dot is authenticated so what I am sick is not authenticated it should be that one otherwise we will override the action wheel over at the response it should be you to be message status code should be forbidden okay so it's done now we need to add wave API controller where we will add some action so we can take a check the token authentication is working fine or not so for adding wave API controller in our application go to your solution Explorer right click on your controllers folder then go add and then click on controller from here we will select web api - controller i'll select empty and then click on add button here I will provide my controller name and Mike is its data controller then click on add water so you can see our Web API controller is created now I will add an action here for getting data from server for anonymous user first so it should be allow anonymous HTTP GET root api's as dieter slash for all means for all user return okay it's just a simple action just I am returning current date time of the server and this action should be accessible for all type of user do not need to authenticate and authorization here now I will add one more action here this action for authenticated user so I will first write authorized attribute because this will check if the request is authorized then this section will book and if not then it will return for 0 1 so it silly result for authorized user II authenticate you so dot if identity okay so what I have done here this action is for only authorized user if the user is authorized then this action will return the authorized version name hello authorized version name okay so I'm going to add one more action here or authorized user only admin user can execute that action so I'm going to add authorize with a nose and the show I'll check from here because I have done static so admin and user if admin user is logged in then this admin user can access this action so it should be admin today's yourself so public Sun result in Kate to secure to take two okay [Music] okay so what I have done here in this section this at this action only allowed for the admin user and if it is admin user then it will return hello and it an admin username and with the rule okay so we are almost done we need to just run this application to check everything is working fine or not okay so let's run our application actually we need one more thing you have or taste or definitely it will get this one four zero four because we don't have any default controller added yoga first so for testing we need to use postman Google Chrome extension first our Web API configuration is ready now we will taste our application with post postman and then in the next part of this series we will create a gorgeous project a client application for consume our web api services with token-based authentication so for test our application in this stage we need to use postman is a postman is a extension of Google Chrome which is used as a client application to taste the request and response between web service and client so first of all I need to run our application or check everything is working fine or not but it will get 4:04 real either because we do not have the default controller now and it's looking for home controller so what I will do I will download postman acts extension from Google Chrome so you can download from Google Web Store Chrome Web Store go to there just click on active Chrome button so it will add take a little time because it is downloading now you can see here it's added now click on that so pain okay so first of all what we will do we will try to access our action which is for all type of user for anonymous user before login let's go back to our equation this is the root for exes anonymous major action so we need to waste you know sorry before this we need to add our vacation URL so this is our application URL then it's a gate method click st. yes you can see here we get response from server the server time is this one okay because this is because of this is for anonymous user but if we try to access this action now for authenticate user then it will show a message authorization has been denied and you can see here the status code is for 0 1 are not authorized and in case if we want to access this method so we should get 4 0 3 so it also returning for 0 1 on unauthorized it let us check once what we have done mistake you can see here it is also returning for 0 1 because the request is not authorized and authenticated now ok so let us try to login to get the authorization token and for this we need to go yoga sorry this is our URL forget the token so what I will do I'll just remove this one this should be our post action and if if we send here then we will get error message because we need to pass username password and contact so from here what I will do I will pass username first I will log in as a user so we can check everything is fine or not so this is user a user type user user and password is all user so let's check with that one user password user and also I need to pass one more parameter here grant eyes it should be password so now if I click on send button you can see here I get access token token type and expiry in so now if I want to execute the method just copy here the access token we need to pass this access token for access restricted resources from server so with this token now we can access this method the for authenticate because it is for any authorized user and we cannot access this one for admin user because I have generated this token for the user type user so let's check it's working on the same way or not so now if I try to access this one authorized if I send them it will get we will get this message because of we have not added the authorized parameter so for authorized parameter we need to first we need to write Varia then we have to paste this token here now if I try to send this button sorry it should be authenticated for authorized user I will get 4:03 because it's not the admin user so this action cannot be accessible with this token because this is only for the admin type of user that's the reason I am getting 4:03 forbidden that means I'm authentic ated but it's not authorized to admin user so if I try to access this just copy this one first and then I try to access the authenticate user means this action which is allowed for any logged in user with that I do the authorize then I will get response so it's showing hello Serratia which means this user so it this for that this user user type user we can access this method because this is allowed for all authorized user and now if we want to access this method so we need to first log in as an admin user and we need to get back the token from server and then we need to access this method with with the token getting from the server so what we will do I will do again I will generate token but this time with the admin user and click on send button you can see I am getting one more token and this token is for admin role user now if I try to access the authorized method this one this authorized method with this token I've just got failure and then token now if I click here then I will get this hello Saurabh model and role is admin means this is now working fine let's check yes you can see here the breakpoint so this method is now working because I have logged in as admin user so everything is working fine now in the next project sorry in the next part of this series we will see how we can use this token-based authentication in our angularjs application ok thank you for watching don't forget to Like comment and subscribe thank you
Info
Channel: sourav mondal
Views: 263,199
Rating: 4.7977777 out of 5
Keywords: Token based authentication, token authentication in web api 2, OWIN, OAuth2.0
Id: rMA69bVv0U8
Channel Id: undefined
Length: 45min 43sec (2743 seconds)
Published: Wed Sep 28 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.