Simplest way to authenticate your Blazor App

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back boys and girls today we're going to be doing cookie authentication with blazer quite frankly their documentation on the topic is quite terrible all they give you is these oidc providers you got to sign in with a token identity server I don't know why they're giving you all this stuff because cookie authentication is super super simple I don't understand why you wouldn't have documentation on this topic and overall their documentation is a little bit all over the place anyway so this is why this video is going going to exist also originally the stuff that I'm going to show you in this video Chris S STI hopefully I pronounced his second name correctly has helped me create this sample application for you and essentially this de demonstration he knows a lot about Blazer I don't he published a book on the thing go ahead and check it out I'm going to leave all the links to his stuff in the description and we can go ahead and get started I will create a new solution in my Patron supporters if you want the source code you will have to come support me on on Patron that is the deal so Blazer cookie authentication is going to be the solution uh the client that we're first creating is going to be the Blazer web assembly app okay let's go ahead and create that without any authentication this will start up let me put this in full screen now uh the first thing that is going to happen is we will want to CD into client let's just make sure that we can run the application and there we have it so if I open this up I get the application all cool let's make this a little bit bigger because well we're going to have to be looking at things if I refresh this uh the page is coming from effectively a development server when you're going to publish this it's just going to be a static file what we want is because we are going to have cookie authentication we are going to want an actual web server with this and chances are you're going to have an API that comes along with this so let's go ahead and add another project this will be our and not a Blazer app but rather a server type of empty you can call this API if you want to but let's go ahead and create this having the server allows you to follow the backend for front end philosophy here all we have to do is add the client to the server and if you watch my spa samples what I would tell you to do is go ahead and add some middleware for proxying your requests to the spa development server here because it's C it can be integrated into the server you essentially just have to add a package which is going to allow you to serve your Blazer app from an as. netcore server we're not going to actually need to R run our client directly so let's go ahead and close this terminal window I'm going to add my or bring up my nugget packages over here since I'm on Windows all of my keybinds are messed up so I'm going to be a little bit handicapped over here I'm going to look for web assembly and server so this is the package that I want let's go ahead and add it to the server once this is added we can go ahead and say app type something like Blazer and you're going to have use Blazer framework files and then for the rest of the endpoints they will really be your API so preferably what you want to do is you want to create a group which is going to be called API go ahead and put this into a variable and now you m get onto this group okay let's go ahead bring back back my terminal over here I'm going to CD into the server and run this there we have it let's go ahead and launch this and first of all nothing is going to display here that's because the Blazer application is actually going to load from this index HTML file over here so what we have to do is we have to say that on the app there should be a map fall back to file and this file is going to be index.html semicolon on the end here let's save this and I will actually have to cancel this application I'll say net watch no hot reload and there we heard so now we have the application but without any of the styling to get the styling you will have to use static files over here that should restart and now we have our full application let's just make sure that the counter is working and it is so just not to confuse if I refresh this uh you still don't get server side rendering right so the components are not being server side rendered this is not the net 8 feature all that we have done here is now our asp.net core API is giving us a Blazer application and it's living on the same address this is no longer just a static file in some kind of bucket right what we want to do next is we effectively want to start creating our end points for authentication so first of all let's go ahead and create an endpoint to display the claims principle which is going to be our user so I will have to import this the one keybind that I managed to remember so for the claims we're going to go to dictionary we're going to extract the key from here or actually this is going to be the claim type and then the claim value so I'm not going to be building up a login form all I want to do is effectively trigger an HTTP request from my blazer application to my server and that is going to automatically put a cookie into the browser so this is a little bit for later right so I'm getting a little bit ahead of myself but another end point that we want to have is map post we're going to be effectively logging in and here you can put some additional information like your user manager your sign-in manager your registration login form Etc I'm just going to say it's blank for now I'm going to assume that whatever form or data you're going to send there you're going to have that relevant thing for your own relevant scenario so we're going to sign in and we're here going to require a claims principle inside the claims principle we're going to have a claims identity inside the claims identity we're going to have claims so in the claims let's just have an identifier we're going to generate a new good just to string this as I struggle with keybinds let's go ahead and format this if you're looking at this and and you watch my previous tutorials you already know what is missing an actual authentication Service so Builder Services add authentication we're going to add cookie authentication and let's just make sure that we call this cookie authentication schema go ahead copy this Value Place it over here we're going to be signing in under this authentication schema so we specify cookie and the identity is coming from the cookie authentication schema as well so we're going to have to say cookie here as well okay amazing so coming back to the client on the right hand side over here I'll have pages and I'm just going to go to Index right underneath hello world I'm going to put a div over here I'm going to place a button and this is going to be my login button uh what to do here you all probably know if you have touched Blazer let's go ahead and create a task this is going to log in in here where we're going to inject an HTTP client this is going to be the client make it a property and then on this client we can post async your login form to the API login endpoints and let me make this post as Json a sync so I can just say look post my empty form or whatever it was you're going to have some kind of result and you may want to process this I'm not going to be doing anything with this so I'm not actually going to uh process this result again because this request is going to be on the browser side and it's interoperating with the fetch API the cookie is actually already going to be stored in the browser by the time you receive result so perhaps here you just want to check has it failed do you get any validation Etc do you need to update the form so that's what you do with the result me personally because I know it's going to succeed I don't need to do anything with it my objective here is to show you the Bare Bones then on on click we're going to have the login Handler and there it is coming back to the browser we have the login button let me clear this and let me just make sure that I don't have any cookies from before it doesn't look like I have let's go ahead to the network T I'm going to log in uh the success code success code the response is 200 and if we take a look at the headers over here and the response headers we have the cookie okay so the cookie is stored in application over here and now because we actually do have this cookie if I open a new tab we're going to go to the API user we're going to be able to retrieve our user because again if you know anything about cookies they get attached automatically to each individual request that you make to the back end so here if we take a look at the default request in the request headers and I collapsed them accidentally here you're going to see the cookie is being attached automatically now we're going to I'm going to look in the documentation because I don't actually remember the names of all these services but you want your authentication State provider and you want your cascading authentication state in order to get these things you're going to need to install a package where it tells you to do that somewhere here so these two over here so let's just uh grab the package we're going to come back to the code commands again go to no get uh let's paste this over here we're going to find the package and this package again because we're authenticating and authorizing on the client this goes on the client okay uh once this is there we want to go to program Cs and register a service so in the Builder Services there's going to be authorization core semicolon on the end and we're going to add another class on here cookie authentication State provider make this inherit from the authentication State provider Implement all the relevant things and this is a task which returns authentication state if we take a look at the authentication State all that it wants you to do is return a claims principle simple enough so what do we do we get our Constructor because we need to make a fetch request to fetch the user metadata we're going to have our HTTP client let's go ahead and inject it in here field hopefully you kind of know what I'm doing here get from Json a sync I will just deser deserialize it to diction AR string string uh api. user so writer already kind of knows what I want to do here this is going to be my user let's format the code and actually want to wait on this and then finally return a new authentication State and here there's going to be a claims principle and then a claims identity and then a bunch of claims and actually this array is something that we want to get from the user over here so uh let's give this a little bit of space on the user this is going to be a dictionary all we're going to do is from the key value pair that we get we're going to generate a new claim so key value key key value value format the code and this should produce our authentication State now we want to register this as a service so we go to client program CS file we go to Services we're going to add a scoped quick authentication State provider and this is going to be an Authentication St provider and actually managed to put these the wrong way around let's go ahead and put it this way semicolon on the end now we have a mechanism for loading user authentication data and if we come back to the documentation we want cascading authentication State let's go ahead grab this we're going to go to I think it is app Razer and wrap the router in this thing so let me cut this place it at the bottom here format the document and there we go so at the moment I think I'm going to get an error because I'm missing a name space so yeah let me refresh uh let's take a look actually add the terminal and if I scroll up a little bit here there is going to be this RZ uh code that basically says that there is an unexpected name over here so all that this is is I'm missing a Import in my imports razor file okay oh didn't mean to open shared let's go ahead uncollapse this bring this in here so using bam format this and there we have it so let's come back to the browser let's go ahead and bring up the network log we're going to clear everything I'm going to actually make it just a little bit smaller I'm going to refresh here and what we're going to see is as the requests goam right at the bottom we're making an automatic call to load the user information and now we're actually going to have access to a claims principle and inside our Blazer application the way that we want to access the claims principle is actually described in the documentation with the authorized view component so if I scroll down authorization authorized view so if you have something like this you can have the context user identity name right so we can grab that let's say we will come back over here I'll take a look at index razor let's go ahead and just whack this over here I'm going to select my first claim of ID so on the context find first is not available so user find first let's grab ID and then display the value okay we'll say that this is your ID let's come back to the browser refresh this we're not going to be able to see the identifier if we come back uh the reason for that if we take a look at the cookie authentication State provider uh I think the reason is pretty crappy you actually have to say uh something in here for the claims identity I'm not sure why you would have this but that's what has to happen so once uh the user is actually loaded you have the user State the rest of the questions that you might have like authorizing based on uh policies roles Etc I'm going to say go to the documentation I think this would be the hardest part of actually figuring out how to wire up your projects in order to obtain that cookie uh one last bit that I would like to show you here is if I H hide the terminal we have our cookie authentication State provider let's say that uh I'm going to go to application I'm going to clear the cookie okay so I'm no longer signed in go to the console and I have object reference not set to an incident of an object if uh the user indeed is null let's go ahead and return a new authentication state with new claims principle and then empty identity that is how you effectively handle that and let's actually say is not because if we send back an empty object potentially it might actually well be an empty dictionary so if uh we don't have more than zero claims you know stuff is bad so refreshing this I don't know what this error is specifically but that basically cleans things up on the UI side and this counts as an empty authentication session now if we go to index Razer what we want to do over here after access a successful login we actually want access to our authentication State provider and perhaps just the cookie authentication State provider what we're going to do is on the client program CS we are going to duplicate this line over here and we're going to register our cookie authentication State provider here we're going to resolve this from a service provider so s SP again as soon as I remember how to type get required service get authentication State provider and that's what that looks like put this brace on a different line now we can use the cookie authentication State provider or on our index to actually inject it over here let's say instead of a client so cookie off or your off service and on the cookie authentication we want to effectively try to log in let's go ahead and generate this method it should be an async task same as the previous one let's come back to index razor we're going to take this we're going to a wait on it here and format the file real quick so logging in will look something like this where we're going to have the client we're going to sign in and if this has been successful this perhaps May return the user or maybe we want to try to load the user this way so private async task we want effectively a factory method though that is going to return us a claims principle and we're going to say get user State a sync take all of this let's cut it place it over here here we're going to return new authentication State and here we're going to say get user State async this is just going to be the user that we want to wait on here and then pass it over here okay so super reusable after a successful login over here we want to do get user State a sync we have our user we're going to await on this here and then we're going to use a on on this and actually maybe a little bit clearer where this method comes from there is a notify notify authentication State changed which is going to accept a task of authentication state so we can actually Supply the get authentication State a sync without awaiting it let's remove this over here and the authentication State let's remove this from here and here format the file a little bit better job on formatting and there we have it so what this is going to give us now is if I refresh I press login and that is going to update my authentication state right after I log in and as I want to log out I want to do exactly the same okay and I think this is pretty much it for this video thank you very much for watching again please go and support Chris it is a thanks to him that I'm capable of bringing you this video as well as my Patron supporters if you would like the source code for this video as well as well as my other videos please come support me on patreon I will be very grateful and a big and special thank you goes out to all of my current Patron supporters if you enjoyed the video don't forget to leave a like And subscribe if you have any questions please make sure to leave them in the comment section I personally have a c horse that is out if you would like to know c as I do highly recommend you take a look at it and with that thank you for watching again and I hope you have a good day
Info
Channel: Raw Coding
Views: 4,459
Rating: undefined out of 5
Keywords: blazor, asp.net core, authentication, cookie, tutorial, guide, csharp, c#, example, webassembly
Id: saQjBorgsA4
Channel Id: undefined
Length: 19min 16sec (1156 seconds)
Published: Sun Sep 03 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.