Adding Facebook Authentication in a .NET Core API (Login & Register)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

My favorite authentication layer to add to web projects is Azure AD B2C. You can configure Facebook, Google, Amazon, or your own email authentication, among others, and the users register in your own Azure AD instance. You have to use the Graph API to do anything specific with the AD tenant instance itself, especially if you're doing anything with groups, which can be a pain, but nothing you can't get around.

👍︎︎ 1 👤︎︎ u/endpointsystems 📅︎︎ Jan 03 2020 🗫︎ replies
Captions
hello everybody I'm making this video I'm gonna show you how you can add a Facebook authentication in your ASP door call application for demonstration purposes I'm gonna use my REST API series as a vessel to implement this feature but you can use this on any type of a speed Oracle application but before we dive into the code I want to make an announcement many of you have asked me what is the ID I'm using it is called Rider and it is made by JetBrains the same company that made resharper right there is an amazing fully cross-platform ID with resharper built into it the ability to use the exact same ID in both Windows Linux and Mac is a very welcomed feature and as somebody who's writing in other languages as well being able to copy my exact same key bindings to other JetBrains IDs I use is awesome even if you are using it just for C sharp I highly recommend writer since I saw that many of you were interested in it I reached out to JetBrains so they were kind enough to give me five free one-year licenses for writer I will be giving those keys away on the 1st of February 2020 and I will be advertising this giveaway in all of my videos leading up to this day in order to participate you will find the link in the description taking you to the registration page you will need to be subscribed to my youtube channel and have your subscriptions publix you can verify you're subscribed you will need to have the sub notification belt turned on and you will need to leave a comment in my video with hashtag JetBrains rider you will find all those instructions in the link in the description down below or in the card on the top right corner of your screen right now this video is part of my HP Norco series you know what I miss any episode please subscribe learning discipline well to get notified when I upload a new episode so as you can see here I'm using the tweet book project from the REST API series and if you're unfamiliar with it we will be building a REST API with a speed Oracle from 2 to 3 now for a year now and it's a pretty feature-rich API you might want to take a look at it if you're not familiar with it but what I've done now is I created a simple website which essentially will be used to login with Facebook to get the token because essentially what we want to do is we want to have a login button below the Welcome message click that button and get the access token which we will use in our REST API and the way to do that is actually fairly simple mock their Facebook has made it quite simple for us and we're gonna take you through the whole process the off workflow that we're gonna go for it goes like this we have our user in you and we use the client-side application can be a website or a mobile app or anything else client-side and then the user will essentially click the button saying login with Facebook and clicking that button will make the user to authenticate and we're going to get back an access token and the client-side application will send the access token to the server-side API to do Nikora API in our scenario and to validate that the token is essentially valid and correct we're going to call the Facebook Graph API and we're gonna say first is this token valid in one call and then give me information about this token things like first name last name the picture or the email and we're gonna use the database or some identity service to validate that the user actually exists in our system or they don't and want it to reg to them so the first thing that you need to do is you need to go to the developer at facebook.com website and this is where you can essentially create applications and sign up as a developer and then you can I go to my apps and say create app and we're gonna name this something like YouTube tutorial but you can name this whatever your application is doing whatever your business is and I'm just going to say create app ID and then just submit it and now I will create my application and I will need to use a product called the Facebook log in product so we're gonna click setup here and we are going to set up logging in as you saw I have a website to do that so I'm gonna use the web SDK but you can use the Android the iOS or whatever else you're using it's the exact same process it's just that you're gonna use a different type of SDK so we're gonna click web first and I'm gonna say what my URL is I'm gonna copy just the local host because that's a testing one I'm gonna say save and then I'm gonna continue and that's going to tell us to set up the Jade and the SDK for JavaScript what you need to do is essentially just copy this code and put it in your website and I'm gonna do that here this is a simple razor page this application so what I'm going to do is I'm going say at section and we're gonna use the script section which will allow me to put stuff at the very bottom of the website here is where it will be rendered so we're gonna close that and I'm just gonna paste whatever code we copied okay and then it tells us that we need to replace two things the app ID and the version the version as you can see on the website it says it's v 5.0 and the app ID is this app ID here so I'm gonna click that to copy and then I'm gonna go back to my code and replace the app ID here and then v 5.0 here and that's all you need to do to set up the SDK on your website now let's follow the next step and see what it says to check the login status we will have a FB dot get logging status method now I'm actually gonna copy that and I'm gonna make my own method in that script section and I'm gonna say at the very bottom function and we're gonna make a JavaScript function called check login state and in that login state what I'm gonna do is we're gonna call that f BG looking status and what I'm gonna do with the response is I'm gonna essentially set the HTML for an element underneath the welcome message so down here I'm gonna say creating you div and give that leave the ID of status and just make this lowercase and that's it so what will happen is whenever I'm getting the login status back I want to set the HTML of that they have to be essentially the JSON response and to do that I'm just going to use jQuery because it's just here I don't recommend or not recommend jQuery it's just something that I can use to set the HTML of a div and then I'm gonna do HTML and I'm gonna say I'm gonna create a code tag to have a little bit of formatting here and then in that code tag we're gonna say Jason dot stringify and then response which is what I'm getting back from Facebook and then not and to have some basic formatting and that's it so now when I click a login button which I'm gonna add in a second depending on my status this off status they will be populated with a JSON object which will give me the access top which I need to login or register to anything else this in this case our REST API so I'm gonna go back here I'm gonna say next and now as you can see this is a check logging State method that we essentially wrote but a bit different here and then I will copy this login button and I'm gonna put it underneath the Welcome message and this we as you see on login check the login state and the scope of this is public profile and email this is sort of the minimum we need we need essentially first name last name and the image of the user potentially and then their email to log them in in our API once we have that we can just go back here and say next and as you can see we just finished there's not much else we need here so to show you what we did I'm gonna stop this installed it again and I'm gonna go back to the website and I'm gonna log in with my own account to get a token so application is running if i refresh you will see that we have a login button now a facebook login button this means we installed it properly and if I just click that you'll see that I'm getting a pop up here saying YouTube tutorial we receive your name profile picture and email address and we say yeah I'm logged in already so continuous Nicholas and what this will do is it will log me in and authenticate me and as you can see we have the author response and we now go an access token the expiry ation the status has connected and some signed request and expires and stuff like that so what I will do is I will copy this token and there is a link I can head where I will get some information about this token and that link is the graph dot facebook.com first last me and then the fields I want and the access token so if I paste that and I click send you see that I get back my first name my last name the picture object email and ID so this is awesome because we can use that token to get back some information for that user who essentially created that token the problem with that is that no were here did we validate that this token was actually issued by our application any application not just you know the YouTube tutorial one could issue a token for this user and the response would be the same assuming you have access to those feelings so what we need to do as well is we need to verify that this token is actually issued by our application and in order to do that we need to use the debug token endpoint where it takes an input token in that case they're talking we want to verify that is authentic and ours and also an access token now this access token can be two things it can either be a valid access token so if I do something like access token is that token and then input token is also the same token because they're both valid I'm gonna get back a response saying that this is a valid token and that it belongs to a user with a specific ID however I won't always have a valid access token because my application would need to be authenticating all the time and keeping track of tokens what I can do instead is on the access token I can delete that and I can go and copy the app ID and go back to postman and put the app ideas the first thing and you and then use the pipe symbol it's this vertical line here and use that and then I will need to go to settings basic and copy this app secret and I will copy that here and then I will go here put it after the pipe and click send and as you can see I'm still getting the response so now I can verify the input token just using the access token as the app ID and the app secret keep in mind the secret is meant to be secret so do not allow anybody to see what this is this application will be long gone once you actually see this video so don't worry about using it so now we know that we need these two endpoints to essentially first verify the token and then get some information from the user we can actually dive into writing some code I'm gonna go to this obligation and I'm gonna stop the website from running because we now have a token that might need to issue that that's fine and I will go to the TWiT book project and this is where we will be implementing the I face book off service so kind of start with that when I go to services and create a new interface and I'm going to name it I Facebook or a service and now this service will need essentially two methods the first one will be returning a facebook token validation result and we will call this validate access token async and this will accept the access token we want to validate and then the other one will be if they were telling a task of Facebook user info result and we're gonna call that get user info async again using a string which is the access token so we need to create those objects and how will they look well we know how they will look because we have the responses here so what I like to do when I don't want to just hand code all that is I use an online service that accepts a JSON object and returns back at C shop class so let's go ahead and do that I'm gonna just type essentially Jason to see shop and I'm gonna go on the quick type dot IO so I'm gonna open quick type and I'm gonna paste my object here and what I'm getting back is a Facebook user info result essentially the whole thing and as you can see it actually generates all the C shop for me so I'm gonna copy the name create the class and I'm gonna do that I could potentially have a new folder called external contracts or something like that let's just call it external and then in it make a folder called contracts and in here we're going to create our Facebook user info result and I'm gonna go back and copy that I need to rename a few things namely the data is actually Facebook picture data but that just copied and we fix it once we copy it so I'm gonna paste that here and I'm gonna import all the statements and this is not picture this is Facebook picture yes rename that and if you want to use it you can use it let's just delete the partial classes we don't really need them and then we need to say this is not data that this is a facebook picture data and that's it we now have the response for one of the things we want back and the other one is this response over here so I'm gonna again copy that go back here put it here see what's the name I want the token validation yeah go back to the website use that and then make the class you could of course make it by hand but I just didn't want to do that to save some time and it automatically added additional property attributes so there's no reason not not to use it it would be what I would do anyway and then the data is will remove the partials and the data is token validation data so let's name it that and that's it we have everything we need now all the responses so what we need to do is essentially create a service that implements these two interfaces and the way to do that is just to use an HTTP client to do the get requests required to that endpoint so I'm going to go about the services let me just copy the name and I'm gonna say add a new Facebook off service and this will be implementing the I Facebook of service interface and let's go ahead and implement the missing members it's you methods so we are gonna have two URLs we're going to use we have a private Const string called token validation URL and this will be what we're going to call to validate the token the debug one and then we're going to have another one called user info URL and then I'm gonna put that here and let's go ahead and copy the end points this is the validation on the debug token and I will need to clear it a bit we're gonna tokenize it so we can do a string format so what it will look like is this we have the debug token one where we need the input token which is the access token and then up ID and app secret and then we have the user info URL which is the me one and I'm gonna go ahead and paste that here and that only has one target now if you wanted different fields you need to change the scope of the token issuing in order to access more information but this is all the basic ones we will need so I'm going to keep it very very simple if you need more you can have more and now we have the two URLs and of course we also going to have a settings object at private read-only facebook off settings object and we're gonna inject that through the constructor and I'm gonna go ahead and create it in the options folder and all this will do is it will have two properties both strings the app ID and the app secret is the other one now since this is a secret I highly recommend you use something like as root key vault or some secret management service don't have this as just plain text but if you have your connection string as plain text I guess it's the same thing so we have that now and I'm gonna go ahead and import that and then we will add the private read-only I HTTP client factory and we're going to use that client factory which is a dotnet core feature to create a to be clients for this service so that's all we gonna need for this now there will be some dependency injection way to register in a second but we're gonna do that once we implement the methods now the first method actually both methods are pretty similar you will have four matted URL which is a spring dot format in this scenario on the token validation URL and then we need the access token as the parameter and we also need the off Settings app ID and then the both settings dot app the secret and that gives us the full URL and then we need the result which is a white dot client factory dot create client dot get async and then we're gonna use the formatted URL to call to get that back of course I would make the method async in order to user wait and now I can just say result dot ensure success status code if it's not success it will throw an exception you might want to have some exception handling here in your scenario I'm just gonna say essentially throw if this is not 200 and then response as string in order to pass essentially the response from the results of content dot read as string async and we're gonna return JSON convert dot deserialize object async as a facebook token validation result from the response as string so this is all our method we do and now the other method actually looks a lot similar to that so I could technically just extract the whole thing it's just used this is copy/paste for now we might want to refactor that later I'm not gonna do that now and now we're not going to format that we're still gonna use the access token but we want to use the user info URL to get the info of the user and again we use the exact same code to do that but we're returning a Facebook user info result and in terms of methods that we need to use to call Facebook to do the token handling that's all we need this plus here so we can go ahead now and create our dependency injection installation for Facebook services I'm going to make a face work of installer here and I'm gonna say I installer if you're not familiar with how we're doing this installation here I highly recommend you check the third episode of my REST API series I explained why I'm doing this but this will essentially register our service and we need to get the settings so I'm gonna make a new Facebook not installer face book of settings object and then I'm gonna configuration dot bind and I'm gonna use the name of the settings and then the Facebook all settings object and then services dot add singleton and I'm gonna use the Facebook off settings so what this will do is the bind method will find a section called Facebook off settings in our app dot settings and we bind the JSON object to this c-sharp class we also need to say services dot add HTTP client and also services dot add singleton I Facebook of service Facebook of service we could make this add HTTP client more specific using a name client I'm not going to do that because that's the only one we have across the whole application now since we did this it's a good time to go to the app settings dot JSON file and create that section and how all the settings looking let's go into the class I'm gonna copy that I'm gonna say baby here face book off settings and the first thing we need is the app ID and the second thing we need is the app secret so I'm gonna put that here and now I'm gonna copy them not from here from this endpoint so the app ID is that paste it here and then the app secret is that paste it here and that's all we need to configure that so now we have all the Facebook all the Facebook configuration already done the other thing we need to do is essentially create the endpoint and create a method for that registration and login now whenever you essentially do a login or signup on a website using some sort of social media you might see that they have a single method for both sign up and login that's because the first time you sign up they will just register you but also log you in but if you're already a member of the website they will essentially just log you in without registering you so we're gonna do the same thing we're just gonna have a log in with Facebook endpoint and we're gonna use that to do both registration and login you can of course split it but the logic will be roughly the same anyway so what we need is we need to go to the identity service interface and we need to add another method here and it will look something like this task authentication result so we're gonna still return our own jot token and refresh token and we're gonna say login with Facebook async and all this takes is an access token and this is the access token that the client-side in our scenario that little website I showed you this one here will be supplying to your API calling the API so let's go ahead and implement that in the derived class which is here let me just minimize these methods a little bit there will be big they could be smaller so we need to implement that we're gonna make this icing because we're definitely gonna need that and the logic in that method goes something like this we first need to validate the token so I'm gonna say validated token result equals to a weight and we need to inject the Facebook service here so I'm gonna say private read-only i facebook off service and we're gonna inject it from the constructor using writers key binding and then i'm gonna say validate access token which is the access token being supplied by the user and now with that here i can say if validation Tucker result dot data dot is valid is false so if it's not valid then we're gonna return a new authentication result which has a single error in it called invalid Facebook talking now of course you might not want to make specific in a realistic scenario what went wrong here and potentially just have a code that your application understands but just for clarity I'm explaining what each scenario can return but it's not a great practice in general so now that we are saying that if the token is invalid return then we can get the user info from Facebook so we we can say VAR user info equals await the Facebook oath service and then get user info using the access token and then we're gonna try to see if this user actually has registered with us before so user manager dot find by email icing using the user info dot email address from Facebook and if the user is null then this means that they're not registered and we're gonna register them now else we already have this user registered and we're gonna generate a token for that so the else logic if you've already logged in it's actually very very simple you just say a weight generates indication results for user async and we use the user object we just retrieved to generate it and the method the generate token method is here you can find that in the description down below I'm not gonna go through how we generate tokens again so if the user is not we're gonna register them so this is where this logic goes and we're gonna say identity user equals new identity user which is the object I'm using for my user it's a default object I'm gonna say ID equals good the new gooood dot to string and then email equals user info dot email from facebook and then user name I'm gonna set it the same as the email like we do for the other users in this application and now we have the identity user from the Facebook user that our system recognizes and we gonna do var created result because we're gonna create the user programmatically I'm gonna say create a sync identity user now you might have noticed that I didn't use a password for this that's because this will be a password less user meaning there's no way to actually log in using a password you can only log in using Facebook if you want to treat this differently and prompt the user to have a password as well of course you can do that and the create user has overloads for things like passwords as you can see here but I'm gonna use the password less one and then if the create result did not succeed then we're gonna say return new authentication result it's essentially the same thing let me just copy that and we're gonna be vague we're gonna say something went wrong now we don't know what went wrong we could see what went wrong using the created result dot errors object but I don't want I'll link to the user what went wrong and then the last thing is exactly the same as this one generates the authentication result using the identity user object here and that's it for this method we have a method now to create or login the user using Facebook so what's left is to go on our controllers or can be found in the controllers folder v one identity controller and I'm gonna create an endpoint for Facebook and I'm just gonna copy the not the refresh one the login one because it would look pretty much the same just calling other things so let me just change that it's not a user login request it's more of a string dot access token and in fact I might as well just make an object for it to make a contract so let's go to the contracts v1 requests and then in here a user face book author request yeah that's enough and then say spring access token here so we have that now and I will use that here so let's just name this again a request and this is the user base book off request and then the identity service we're just gonna call the login with Facebook and we're gonna use result dot access token to register or login and the rest of the code actually stays exactly the same because our method still returns and authentication result and that's it so now we need to just change the URL so instead of logging I'm gonna say when I create a new one I'm gonna say just Facebook off and then potentially just off through boo or Facebook and I'm gonna change that and then I'm gonna say as well Facebook off here and that's all we need to do so now I'm gonna run this website in the background so this is now running and I'm also gonna run the API so I'm gonna debug that and this should also launch swagger and in order to see exactly what's going on I'm gonna put a breakpoint here I'm gonna take you through the whole journey so let's just go to swagger and as you can see we now have the off with Facebook and I'm gonna click that and I say try it out and as you can see we need an access token so let me refresh that page okay so this imagine being your application your website your iOS your anything and then you just click login automatically logs main gives me a new valid token and copying that token in your code you will be doing this programmatically and I'm gonna use that to call the API here so I'm gonna execute this and I'm gonna go and see that I hit a breakpoint and my request object has the access token so let's go we're gonna go in the identity service we've make this a bit bigger and we have the access token and the first thing we need to do is validate it on Facebook and this will format the URL called Facebook and as you can see it it returns that the token is indeed valid and it expires at a specific time we don't really need to care about the expiration because if it was valid once it is the user authorized but once in a while you might want to force the user to do it again for security purposes now since it's it since it is valid we're not going to go in here and we're going to get the user info and this is the call to Facebook again and as you can see I'm getting my email back my user ID my facebook picture everything is coming back and then I'm gonna see if the user actually exists in the system the user is not meaning it's not in the system so this will essentially create a new me and you can see that it's called just succeeded in the result meaning it registered me in the website and I'm just gonna generate a new token and return here so in the front end you can see that the response has a token and a refresh token meaning I was successful into registering with Facebook and if I go to job dot M s I can just put the token and see that it is as valid as any other token we generated we have a email we have the JWT ID my email here again exploration and all that and the user ID and of course if I call the same endpoint again with the same access token because I am now registered in the system as you can see in the method I'm still validating and all that but the user called to the identity service will return that I am actually a registered user so it's gonna go just to the generate authentication result for user and I'm gonna get the token back again with a new token so that's all very simple very easy you will find the code for this in the description down below don't forget to register for the JetBrains rider giveaway special flex magnet have sponsors for making these videos possible if you want support me as well you're gonna find the link in the description down below leave a like if you like this video subscribe for more like this I ring the bell as well together to fight when I upload a new episode and I'll see you in the next video keep coding you
Info
Channel: Nick Chapsas
Views: 23,300
Rating: undefined out of 5
Keywords: Elfocrash, elfo, coding, asp.net, .netcore, dot net, core, C#, how to code, tutorial, asp.net core, javascript, js, csharp, rest, rest api, lesson, software engineering, microsoft, microsoft mvp, .net core, auth, authorization, jwt, jwt token, json web token, registration, user, user registration, nick chapsas, web api, facebook, facebook auth, facebook login, facebook register, access token, .net core 3, .net core 2, .net core 2.2, authentication, dotnet, .net
Id: I2PChWTwmM8
Channel Id: undefined
Length: 33min 28sec (2008 seconds)
Published: Thu Jan 02 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.