No video

Using the HttpContext in Blazor Server the right way

  Рет қаралды 12,476

Codewrinkles

Codewrinkles

Күн бұрын

In one of the previous videos we have showed how can we access the HttpContext in different #AspNetCore app types. Blazor Server gets its own video as the Blazor hosting model is so different that it needs a more detailed attention. The major problem is that in Blazor Server we can't access the HttpContext directly, as it is not guaranteed that IHttpContextAccessor will have an instance of the context and it is also not guaranteed that if it has an instance, it is the one that was used when creating the circuit. In this video we take a deeper look at the Blazor hosting model to then showcase how we can take a snapshot of the HttpContext information and make it available to the entire Blazor Server app.
#Blazor
Chapters
1. Intro: 00:00
2. What's different in the Blazor Server hosting model? 00:46
3. The Blazor Server hosting model in action: 04:11
4. Can we use HttpContext in Blazor components? 14:33
5. Creating services and initial application state: 17:20
6. Capturing HttpContext snapshot: 19:22
7. Passing captured HttpContext state to the Blazor root component: 22:29
8. Using state information in Blazor components: 25:55

Пікірлер: 68
@calin534
@calin534 2 жыл бұрын
This is soo nice, simple and useful! Another Blazor aspect that is obvious. Thanks, Dan!
@Codewrinkles
@Codewrinkles 2 жыл бұрын
Based on recent comment I think there's the need of a very IMPORTANT clarification. If you just want to get the authentication state and what's in the ClaimsIdentity in the HttpContext, then it's actually the best way to use the AuthenticationStateProvider. I have used this as an example because it was easier and more straight forward to showcase how we need to proceed if we need to capture HttpContext information. Because there are scenarios that are not covered by the AuthenticationStateProvider service. For instance if you need to extract information from the headers, like an access token, or anyting else that is outside the User property in HttpContext. The AuthenticationStateProvider is actually wired up similarly to what I have described in this video. In your App.razor everything is enclosed by the CascadingAuthenticationState component. That component populates the scoped instance of AuthenticationStateProvider with information that it retrieves from the HttpContext. So as a summary, if you just need access to identity information that's inside the "User" property of the HttpContext, then you should use the AuthenticationStateProvider service and you really don't need to care about the risks that I have outlined in the video. If you need other information, then you need to capture the state of the HttpContext and pass it as a param to the app itself, like I did in this video
@goranmaric6806
@goranmaric6806 Жыл бұрын
I really like Blazor Server, but there isn't a lot of content available for it. Usually, people always write or speak about WASM. You are one of the few who post content about Blazor Server, and the topics you cover are genuinely real-life scenarios. In your videos, you address almost every problem I encounter while working with Blazor Server. So, thank you for your work.
@Codewrinkles
@Codewrinkles Жыл бұрын
One of the nicest comments I ever received. Thank you for watching. Aso this motivates me to maybe start doing Blazor stuff again. Recently i didn't create much about Blazor Server.
@LuisBragagnolo
@LuisBragagnolo Жыл бұрын
Hey! Thanks for the video, it did bring me clarity to the HttpContext topic. I had a question but I found your video "How to implement authentication in Blazor Server from scratch" that answered that question. Thanks again!
@samsacheti
@samsacheti Жыл бұрын
This is such an amazing explanation. Thank you very much!! I had wasted hours trying to understand the same by reading through Microsoft Documentation
@Codewrinkles
@Codewrinkles Жыл бұрын
Yeah, unfortunately for this aspect the documentation is not easy to follow and understand. Glad this video cleared some things up for you.
@MarcioJMAndradeTube
@MarcioJMAndradeTube 9 ай бұрын
Great explanation! Better than any other tutorial I found.
@godfredboateng1669
@godfredboateng1669 10 ай бұрын
Hey sir! we love your format! If the theory is good, it makes u able to go crazy at stuffs and implement thing to suit your particular need!
@torrvic1156
@torrvic1156 Жыл бұрын
Thank you so much for your hard work, Dan! That was really very interesting.
@Codewrinkles
@Codewrinkles Жыл бұрын
Glad you enjoyed it!
@netmerge7083
@netmerge7083 2 жыл бұрын
Great information!
@user-vi7xn1tj9f
@user-vi7xn1tj9f 2 ай бұрын
Very nice, but still a workaround of sorts. Would be nice all those features to be exposed without writing all of the extra code.
@oncalldev
@oncalldev 7 ай бұрын
Excellent explanation.
@moriluca90
@moriluca90 2 жыл бұрын
Thank you for your time.
@stanyurynets6258
@stanyurynets6258 2 жыл бұрын
Great job!
@thorium9098
@thorium9098 Жыл бұрын
Well explained. Thanks!
@Codewrinkles
@Codewrinkles Жыл бұрын
Glad it was helpful!
@cskmorfeas
@cskmorfeas Жыл бұрын
Simple and nice, thank you
@Codewrinkles
@Codewrinkles Жыл бұрын
Glad you like it!
@ysz10000
@ysz10000 Жыл бұрын
This is very nice explaination and very easy to undersatnd. Thank you so much.
@Codewrinkles
@Codewrinkles Жыл бұрын
Glad it was helpful!
@kevinmaguire1845
@kevinmaguire1845 Жыл бұрын
Great work man.... nice explanation .. thanks!
@Codewrinkles
@Codewrinkles Жыл бұрын
Glad it was helpful!
@1111111yeah
@1111111yeah Жыл бұрын
So useful, thank you 🍻
@Codewrinkles
@Codewrinkles Жыл бұрын
Glad it was helpful!
@devzen_8520
@devzen_8520 10 ай бұрын
Very nice, thanks.
@Codewrinkles
@Codewrinkles 10 ай бұрын
Most welcome
@rick5522
@rick5522 11 ай бұрын
Thanks, awesome video! Anyone who tries in .NET 7 Blazor server. They changed the Layout template so you only have to add that @{} code block without setting layout. _Host works the same way as an entry point mentioned in the video!
@TrotterSoccer
@TrotterSoccer 2 жыл бұрын
Great!
@ahsanbutt373
@ahsanbutt373 Жыл бұрын
Definitely this video was useful.
@Codewrinkles
@Codewrinkles Жыл бұрын
Glad to hear it!
@hfpsc27
@hfpsc27 2 жыл бұрын
Thank you. If I have a blazor webassembly could I use the same authentication that the server uses, to work has a single sign on?
@eliodaniele7979
@eliodaniele7979 2 жыл бұрын
@Codewrinkles Hi! First of all, thanks for sharing this material. It's the best material that I ever found. I have an issue. When I click on the navbar, the _Hosts reload and clear all the params that I saved there. (For example some data from DB that I want to set on the entire app context) . Is there a way to save data, and avoid the reloading? Thank and kind regards.
@yurandejesus7656
@yurandejesus7656 11 ай бұрын
Thank you so much! It was really really helpful. If I may, let's say I want to pass something that I don't have in HttpContext such as the Username but I need this value to persist in the database. How can I do it? Thanks in advance.
@hectorcontreras9171
@hectorcontreras9171 2 жыл бұрын
Shouldn't the setting of the _identity (IdentityInformation) variable from InitialState In App.razor be done in OnParametersSet() instead of OnInitialized()?
@dajma00
@dajma00 2 жыл бұрын
Very nice piece of information. But cant we just use to achive the same thing?
@jankool01
@jankool01 2 жыл бұрын
Thanks.
@Codewrinkles
@Codewrinkles 2 жыл бұрын
You're welcome
@korbashi123
@korbashi123 Жыл бұрын
Thanks
@Codewrinkles
@Codewrinkles Жыл бұрын
You're welcome
@kaihusravnajmiddinov5413
@kaihusravnajmiddinov5413 Жыл бұрын
Hey man, you deserved a like. For that i had to log into youtube, though i wasn't until went through your video. I logged in just to click like for your video. Very very good pedagogical explanation.
@Codewrinkles
@Codewrinkles Жыл бұрын
Hey, thanks
@MMGator
@MMGator 2 жыл бұрын
I changed our application to remove IHttpContextAccessor and applied what you did here. I am able to log in, but when I get to my home page, I get 'The list of component records is not valid'. It goes through the OnInitializedAsync just fine and gets the data from the db, but the page renders halfway and I get that error. Everything I've researched says to either turn off caching in the response headers (doesn't work) or to check my parameters on the page (there aren't any). Any ideas or pointers on what to look at? I'm at a total roadblock.
@ezmooj
@ezmooj 8 ай бұрын
Thnaks for video can we extend blazor server identity authenticated lifetime? its default only 15 minutes if user currently on site if 15 minutes near ending how we can extend this?
@adam-xt8te
@adam-xt8te 3 ай бұрын
It requires a little update. There's no _Host.cshtml file and OnInitialized is hit by debugger in every file: App, Routes, MainLayout and Home.razor. After adding @render InteractiveServer theres no hit in Home after clicking Counter
@raphaelmt1706
@raphaelmt1706 9 ай бұрын
Two questions: - Can we capture cookies from a http pipeline middleware and copy them in a scoped service instead? - Will the parameter aproach only work if the ServerPrerendered mode is used?
@mluhring
@mluhring 8 ай бұрын
What will happen if the Blazor service you created just accepted the whole HttpContext for that circuit rather than just values from the HttpContext? I have been trying to find a way to set a response header Clear-Site-Data to clear user cached data for the site. I am thinking we might be able to set the header on the initial page load when the circuit is created. Maybe only do this when a query string parameter is sent.
@ButuGruv
@ButuGruv 28 күн бұрын
Is there a way to do this in the new .NET 8 Blazor Web App?
@Mateusz-tu9mt
@Mateusz-tu9mt Жыл бұрын
Hi, one question - we're using HttpContext in blazor via accessor for redirections, the context isn't guaranted to be available, so we shouldn not use it evem for that simple scenario, right?
@Codewrinkles
@Codewrinkles Жыл бұрын
Yes, that's correct. You don't have any guarantee of any kind on the HttpContext in Blazor Server. Only the first time the app/circuit is loaded you can rely on that. You can use that initial information, and create a StateManagement Service in your app. You set the initial state from the context, and then you change that state whenever your business logic would require it.
@krasimirstoyanov3676
@krasimirstoyanov3676 2 жыл бұрын
@Codewrinkles Is this approach only working with users stored in SQL db? I have MongoDb and the User in HttpContext is always null. Thanks.
@Codewrinkles
@Codewrinkles 2 жыл бұрын
The user in HttpContext doesn't have anything to do with the persistence store itself. When a user is authenticated we set an authentication cookie. For each subsequent request, the User in HttpContext is constructed based on the information found in the authentication cookie. If it is null, it means that there is no authentication cookie. Or that it is not the default one and Asp.Net Core doesn't have enough information to create it.
@SibTiger33
@SibTiger33 Жыл бұрын
Fantastic video - So would it then be possible to cache and keep a user logged into the app using this technique? (i.e caching a token or something unique to the user in protectedLocalstorage or protectedBrowserStorage)
@Codewrinkles
@Codewrinkles Жыл бұрын
If you're using Blazor Server, then you actually don't need to persist anything. You'll just need to make sure that you keep the AuthenticationStateProvider updated. There is an entire playlist on Blazor Server Authentication only and I think you might find it useful to go trough all the videos there.
@SibTiger33
@SibTiger33 Жыл бұрын
@@Codewrinkles Sorry what I mean is if the user closes the browser window - when they close the window the circuit closes and the user will have to log back in again (*i'm thinking about mobile users especially in which the browser is often closed) - So in those cases if you wanted to keep the user logged in for x amout of time you could use local storage to store a key and expiry information and potentially recover that information in the OnAfterRenderAsync on the App.razor whilst using your technique above ? What do you think? (so in the onAfterRender method you could check local storage find the necessary keys and rebuild the user and send the information to a custom method in a custom AuthenticationStateProvider) 1. create a custom AuthenticationStateProvider that knows how to build a claimsprincipal from a custom user object 2. Use your method above for updating app state 3. When user logs in save a key / expiry in localstorage 3. implement some custom logic in OnAfterRenderAsync within the App that checks if the user is authenticated - if not then check localstorage for a valid key and checks the key as not expired (if expired then delete it) 4. call method in custom authenticationStateProvider to re-log user in *Using ProtectedLocalStorage *Update: I just ran a quick test and this does indeed work... But do you think there is better ways of keeping a user logged into a blazor server application for x amount of time when they close the browser ?
@BernardPhua
@BernardPhua 2 жыл бұрын
Instead HTTPContext, if we use AuthenticationStateProvider component to get the User Identity info will it also have the same security concern?
@Codewrinkles
@Codewrinkles 2 жыл бұрын
Thank you very much for your question. I think I have also discussed this in one of the previous comments. If you just want to get the authentication state and what's in the ClaimsIdentity in the HttpContext, then it's actually the best way to use the AuthenticationStateProvider. I have used this as an example because it was easier and more straight forward to showcase how we need to proceed if we need to capture HttpContext information. Because there are scenarios that are not covered by the AuthenticationStateProvider service. For instance if you need to extract information from the headers, like an access token, or anyting else that is outside the User property in HttpContext. The AuthenticationStateProvider is actually wired up similarly to what I have described in this video. In your App.razor everything is enclosed by the CascadingAuthenticationState component. That component populates the scoped instance of AuthenticationStateProvider with information that it retrieves from the HttpContext. So as a summary, if you just need access to identity information that's inside the "User" property of the HttpContext, then you should use the AuthenticationStateProvider service and you really don't need to care about the risks that I have outlined in the video. If you need other information, then you need to capture the state of the HttpContext and pass it as a param to the app itself, like I did in this video. Sorry for the long answer, but I hope this clarifies your concerns.
@BernardPhua
@BernardPhua 2 жыл бұрын
@@Codewrinkles Thanks for the detailed explanation. This is good info. 👍
@shawnafisher4547
@shawnafisher4547 4 ай бұрын
Ok I created a blazor server app and my _Host.cshtml does not look like that, it has html in it. I'm confused.
@DjimmyTrovy
@DjimmyTrovy 4 ай бұрын
You are probably using .NET7 and the version shown in the video is .NET6. In .NET8 there is no _Host file. If you are starting a new app in Visual Studio and want to use .NET8 just use the "Blazor Web App" template instead of the "Blazor Server App" template.
@adrien8768
@adrien8768 2 жыл бұрын
I use the httpcontext in the app.razor to redirecte if not login. So this is not correct ?
@Codewrinkles
@Codewrinkles 2 жыл бұрын
Strictly speaking, no, that is not necessarily correct due to the reasons. For a basic check if the user is logged in or not, you can use the AuthenticationStateProvider service that you can inject in any component. What that service does is actually take the information from the HttpContext. If you use the HttpContext in App.razor, then you run into the risks that I mentioned in the video.
@Codewrinkles
@Codewrinkles 2 жыл бұрын
The authentication state provider is provided, as far as I know, by the CascadingAuthenticationState component that wraps everything in App.razor.
@Codewrinkles
@Codewrinkles 2 жыл бұрын
There are however also scenarios that are not covered by the AuthenticationStateProvider. For instance if you integrate with 3rd party APIs you might want to extract the access token to use for that API. That access token might be in the headers or in a custom claim. In this case I guess the best way to proceed would be to extract the needed information in the Host.cshtml and pass it as a param to the App component.
@Tymonello
@Tymonello Жыл бұрын
Leaving a comment doesn't help you as much as you are helping us to understand programming!
@Codewrinkles
@Codewrinkles Жыл бұрын
You'd be surprised how much engagement on a video matters :) Please also check my newest videos as I have done some improvements to the image quality and sound.
Using EF Core in Blazor Server the right way
33:49
Codewrinkles
Рет қаралды 21 М.
👨‍🔧📐
00:43
Kan Andrey
Рет қаралды 7 МЛН
Kids' Guide to Fire Safety: Essential Lessons #shorts
00:34
Fabiosa Animated
Рет қаралды 10 МЛН
EVOLUTION OF ICE CREAM 😱 #shorts
00:11
Savage Vlogs
Рет қаралды 14 МЛН
Викторина от МАМЫ 🆘 | WICSUR #shorts
00:58
Бискас
Рет қаралды 6 МЛН
Intro to Blazor Hybrid (.NET MAUI Blazor)
37:18
IAmTimCorey
Рет қаралды 60 М.
EF Core in Blazor Server with repositories, services or CQRS
31:57
Claims based authorization in Blazor Server
20:10
Codewrinkles
Рет қаралды 6 М.
👨‍🔧📐
00:43
Kan Andrey
Рет қаралды 7 МЛН