Blazor Tutorial : Authentication | Custom AuthenticationStateProvider - EP12
Vložit
- čas přidán 11. 09. 2024
- Hey Coders,
Subscribe here - / @curiousdrive
Talk to us on - / curiousdrive
Like our page - / curiousdrive
Follow us on - / curious_drive
Follow us on - / curiousdrive
Make a donation - www.paypal.me/...
Be a member - / curiousdrive
Find Code here - github.com/Cur...
In this #Blazor tutorial, I am going to show you how you can implement #AuthenticationStateProvider and have custom authentication for your blazor app
Blazored - github.com/Bla...
Content -
1. app.UseAuthentication() & app.UseAuthorization()
2. AuthenticationStateProvider
3. AuthorizeRouteView & CascadingAuthenticationState
4. AuthorizeView, Authorized and NotAuthorized
5. #NotifyAuthenticationStateChanged
6. #Blazored.SessionStorage
#CuriousDrive #WeLoveCoding
Code - github.com/CuriousDrive/BookStores
Thanks for watching, please share with your friends :)
Thank you 🙏
Wow -> why has this not gotten more views??? Every other "Blazor authentication" just uses the restrictive scaffolding - this video actually shows how to do it custom. This is a great video! thank you
I know right? I am glad that you like the video Ian.
Yes, I was gonna say that tooo 😅 Thanks for the detailed explaination ❤
This is an amazing video. I have a whole team wrestling with this and you hit every nail on the head that is missing from the docs and Stack Overflow pertaining to integrating custom login routines w/ Blazor.
Well done sir. I cannot thank you enough.
Thanks Jerrod. That's a lovely feedback. I am sharing the blog where I learned this from. Hopefully it's helpful :)
chrissainty.com/securing-your-blazor-apps-authentication-with-clientside-blazor-using-webapi-aspnet-core-identity/
This is quite literally the only resource that explains the basics excluding Entity framework, top job
Thanks for watching and commenting David.
This video does a great job of filling in the missing gaps in the Microsoft Documentation. It was exactly what I was looking for. Nice job!
Thanks for a lovely feedback Jason. Please share with others.
Its a good alternative to secure a Blazor app from the Microsoft approach to do authentication, but the MS approach as a lot of advantage, like fined grained authorization, permission, external authentication, oauth... and all that functionalities are already implemented (by default it use EF but with a bit of work you can bring you on storage) for you. Then you just have to configure it. If one day you have to add complex authentication/authorization flow you will need to write a lot of code to achieve what microsoft give you out of the box and also written by OWASP expert.
I hope to see another tutorials withe Identity Server both on WASM client/server side Blazor without Entity Framework (MongoDB, Redis, ...)
Your content is excellent, keep going on.
Thanks for a commenting Giullaume. I will add that to my list.
Hey, just wanted to mention - this helped me out a lot on my first blazor app when I hit a wall on the Authentication. Your speaking, content and pace of the video is perfect. Keep it up! You have a new subscriber !
Thanks for subscribing Neil. Please share with others too. :)
As everyone else has said, this video was super helpful! You're the only resource I've found that walk through how to add custom authentication without the restrictive scaffolding. I'm also really glad you showed Blazored, I'd never heard of it.
was looking something like that for few days, this video has got already 2years and its best. Everyone using only Identity library which is stupid with Blazor server SignalR in my opinion. You showed us both ways and you won.
Thanks baq. I learned it from this blog - chrissainty.com/securing-your-blazor-apps-authentication-with-clientside-blazor-using-webapi-aspnet-core-identity/
Hi, thanks very much for producing this video for Blazor WASM developers. I have done a lot of work on Blazor server side applications and really struggled to get started with Blazor WASM login module. This video was very helpful to me. Thanks very much, A very BIG thank you.
Thanks for watching Thusantha. Please share with others too. :)
Great stuff. I've been struggling with this for weeks. There's a lot of incorrect information out there on blogs and other places. Thank you!
Grant, I know right? I worked on this demo for 2 weeks to get it work right. One of my favorite demo. Glad it was helpful.
My users are going to be asking me for authentication across tabs. They often "open link in new tab". It would seem that Cookies would be the answer here but I'm not sure how you would do this in a Blazor app without generating a postback (which means a Controller somewhere in the mix). Have you seen any other implementations? LocalStorage doesn't appear to be the answer because you can't specify an expiry date anywhere there, so it would seem that if you are using LocalStorage, once logged in, always logged in.
@@grantmaw I haven't seen any samples using cookies to store the state. But you definitely made me curious about this. In my next video I am going to give demo on Layouts. I could do some research once I am done with Layout demo.
@@grantmaw Have you checked out this?
stackoverflow.com/questions/54024644/how-do-i-create-a-cookie-client-side-using-blazor
@@CuriousDrive I have finally got back to this. I've figured out how to get a user signed in and for the authentication cookies to be set on the browser which allows us to open links in a new tab. You need to direct the user to a normal razor page with a form that generates a http post in order to set and remove the cookies. Problem is, if I have 2 tabs open, and I logout in say tab B, this works, but tab A is still logged in. Working on it, will let you know if I manage to work it out.
Finally I understood how this works and implemented it. Thanks a lot for this vid!
Thanks for watching Martin. Please share with your friends.
Excellent video on this topic! Saved my day as I was attempting to do the same on my own and couldn't find any good examples until I found this. Thanks for the great video!
Thanks for watching Benjamin. Please share with your friends :)
This is awesome! I have a special use case where I am building apps within a walled garden and I don't really need to authenticate users. I just want to collect a user ID provided by our environment after the user is already authenticated (WSSO). I then use that ID to lookup the user and I know everything I need to know about them.
It took me a few days of going through all the Identity overkill that's out there to arrive at this very simple and elegant solution.
Thank you! This will be implemented in several applications going forward.
Thank you for lovely comment srHunter.
I don't usually like videos when the speaker has an accent because they usually talk too fast as well making it difficult to understand, but you articulate your steps so well and at a good pace that I forget that you even have an accent. Keep up the good work and don't change your style!
Thanks for the kind words. I want to get better.
Thanks Curios Drive, I'm testing blazor server and it's very interesting, your example is really usefull, I'm going to see your code and I'll tell you my comments in a few weeks. Thank you very much for sharing with all the community your knowledge. Regards from Mexico.
Manuel, thank you so much for a lovely comment. Thanks for watching. It's always nice to hear that the course helpful to others. Please share with your friends :)
I'm so happy I found this
It just took me revisiting various parts of the video multiple times, but I now finally understand how this works.
Thank you very much for sharing that knowledge!
Thanks man. You just saved my day. I was actually breaking my head to achieve this but your Tuto made as that simple.
Thanks Subair. I am glad this was helpful. Please share with your friends too
This piece is an absolute life-saver man. Thank you for this.
Thanks for a lovely comment Arthur. You made my day :)
Please share with who might need this.
Actually legit useful, and great! thank you so much. CZcams algorithm do blazor devs a favour and up this post.
I know right? let's get that algorithm running :)
Thanks for a lovely comment. Please share with your friends.
Very helpful indeed even 3 years later 👍
Fantastic tutorial! I was really hoping to avoid Entity Framework in favor of Dapper and this allowed me to accomplish that... Thanks!
Yes. That's the goal of this video. I am glad that you were able to do without using EF Core.
Just what I was looking for, thanks! I don't Entity Framework and all other examples seem to assume everyone does use it.
Thanks Jim, Yes it does not matter which ORM framework you use. It should work with any one of them.
Awesome please keep up the good things.
Thank you very much.
The one downside to using server storage is changing the app's render mode to Server which negates a lot of the value of using a Blazor Server layout in the first place. Render mode being ServerPreRendered meant a page could load the HTML / CSS / JS first then the c# logic which tricks users into thinking the entire page is loaded when it's not. With render mode being Server, the entire page now has to load including logic, so depending on the page it may take a moment or longer for the user to see it. Of course there are problems with using local storage but at least then you can still take advantage of Blazor Server's prerender mode.
Thank you for this one. Really needed/helpful!
Thanks for the guide.
I would just like to point out that session storage is not secure.
You can try this by logging in, then opening your browser's developer console and navigate to Storage > Session Storage, and you can edit the email to be any email that you want. After refreshing the page, your email will change.
I suggest to encrypt your data before storing it in session.
Good observation Shyrtex, The reason why I did not encrypt the email address is because going ahead in the series I am using JWT tokens to communicate between API. And I am storing JWT tokens in the local storage instead of email address.
You can get user's email address by their JWT token. Not sure if you are following the Web API series that I worked on, there I am explaining how JWT tokens work. Please check the link below.
czcams.com/play/PL4WEkbdagHIQVbiTwos0E38VghMJA06OT.html
@@CuriousDrive I am familiar with JWT. I found this video by searching for Blazor authentication since I was having difficulty finding an example of a practical custom implementation of the AuthenticationStateProvider.
I will have a look in the further videos to see how you implemented it with JWT.
Great content here!
Thanks for watching the video Shyrtex, I hope you enjoy other videos too.
Let me know if you have any questions.
❤ Great Job. Keep making videos on blazor with updated content.
Thanks for watching the videos, Hamid. I am going to make 4 more videos on this series. And in May I am going start series on Blazor WebAssembly which will have more advanced topics and controls so stay tuned!!!
@@CuriousDrive I will stay tuned.
It's exactly what i needed. Great content!
Thanks for watching Fernando. :)
This really helping me out, thankyou very much
Thanks for watching. Please share with others too.
CustomAuthenticationProvider with localstorage works fine when you run localy. But when you deploy to Azure you will have errors and cannot run your app:
Console erroror:
Error: The circuit failed to initialize.
e.log @ blazor.server.js:15
blazor.server.js:1 Uncaught (in promise) Error: Invocation canceled due to the underlying connection being closed.
Why?
This is a really helpful brother.
thank you for this great video!
Helps me a lot :)
Thanks for watching AndiM. Please share with others :)
For this episode, did you start with the same solution as in EP11? Otherwords, create the solution with auth?
BTW, just subscribed. There is plenty of "stuff" out there on the basics of Blazor, these advanced topics are extremely useful. Keep it up. One topic I need for Identity, is how do I enriched the user object after authentication? For example, After login, using EF get a list of other User related objects pulled from the database and added to the Scoped User class/object? In my case I have a set of permission scopes, for example, user ABC can only see customers in the USA, and user XYZ can only see customers in India. I don't like using claims for this I use the resulting Lists in linq joins.
Hey Scott,
No. I actually created a new solution just for EP11 to explain how authentication works which comes out of the box. For this episode I used the same solution that I have been working on from EP01-EP10. I want to build a project which has all the feature an app should have.
Scoped instance is a solution but you would lose data every time user refreshes the page. Maybe you can encrypt all the information and store it in session/local storage? or URL? Or you can do server side storage in SQL?
Thanks for subscribing. I am still new at this and learning. Please share the content with your friends :)
hi, i followed your steps, but i have an error that didn't happen to you. InvalidOperationException: No signing credential is configured by the 'IdentityServer:Key' configuration section.
Do you know why is that error?
Hello Matias, It looks like you are using some part of IdentityServer which I did not use in this demo. I did talk about IdentityServer in the last video. But I am not using any of the code from last video. Maybe you still have that code?
Do you have a video that shows a custom way to register and persist users to sql?
Hello Buddy, quick question. On the _Host.cshtl, I am getting a red swiggly on "". This is for: @(await Html.RenderComponentAsync(RenderMode.Server)). It says that the type or Namespace name 'App' could not be found. I wonder if I am missing a reference or something. Thanks for your help.
Did you clone/fork my GitHub repo or you are getting error on your project?
What version of .net core is installed on your machine? And what version is the project pointing to?
@@CuriousDrive Hello my friend. I created a new project in Visual Studio from scratch and suspect that I might be running different version of blazor. And I copied some of the code from your GitHub repo, but also been following along step by step via your youtube videos. Do you recommend that I clone your GitHub repo. I'm not familiar with that process, but it is def something I will look into for the sake of consistency. Thank you again for the excellent videos and super quick response to questions
New Project from Visual Studio should work fine. I'd try cloning and see if I get the same error or not.
And I am here to help. Sharing my channel with others would make my day. Thanks for watching.
man you are a life saver! Thank you very much
Thanks for watching Shexany. Please share with your friends :)
Hi , Great job. I am getting this error while running the application "InvalidOperationException: JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendererd. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method." CustomAuthenticationStateProvider => Error is throwing from this line await _sessionStorageService.GetItemAsync("emailAddress"). Am i missing some thing ?. Please help!
Did you change the render mode to server after installing session storage?
@@CuriousDrive Thanks a ton :) ... I forgot to change... Now its working fine :).
Appreciate your quick response
Here to help 😊.
Tks you. Can you speak loudly ?
I have been editing to 20 decibels. I should increase that. Thanks for the feedback!!
Thanks for the video, it was helpfull, keep awesome!
Why id you add CascadingAuthenticationState in the NotFound Section in your Router rather then on the top ??
Honestly it's been so long that I don't remember why I did that. But it looks like I did it the right way in the Blazor WASM series. Please check the video below.
czcams.com/video/B9jKf-Dn0Yg/video.html
Great tutorial, one question: Can't the session storage be easily modified by anyone in dev-mode to fake a login?
Great video. Could this code be modified to work with Blazor WASM, or should a different approach be taken? Thanks.
Hey Paul, I actually made a video explaining how this could be done for Blazor WASM apps. Please check this video. czcams.com/video/B9jKf-Dn0Yg/video.html
Excellent
Thanks Deepak. Please share with your friends :)
This is excellent, but as is its very insecure (someone can just add a session key with the email address). What is a good way to make it more secure?
more secure way would be to store cookies or Json Web Tokens as user sessions. I have covered both of those topics. Please check below videos. These are different projects though
czcams.com/video/rn2gp5VNGKI/video.html
czcams.com/video/B9jKf-Dn0Yg/video.html
Great tutorial, easy to follow and understand. I have one question though: if I go into dev tools in the browser and manually add something under the "emailAddress" key I still get authenticated. Is there any solution to this problem?
In the perfect world, I would get token from my API if the user is authenticated. And get user data from token every time user refreshes the page. If someone changes the token then user won't be valid. I haven't tried it personally but sounds like a solution to me.
@@CuriousDrive I see. But given that this is server side blazor let's say that I don't want to create API for the app. Does the asp identity really allows for such workarounds as manually inserting key into session/local storage and pass login screen and authenticate (becouse it seems like a serious security flaw)?
I don't think ASP.NET Identity cares about how you store state and user info. It leaves it up to us what logic we want to use to pull user information. We can store it using Dependency Injection, SQL Server, URL, Cookies, Local/Session Storage..... Sky is the limit when it comes to security.
@@CuriousDrive Got it. Thank you for your help!
Thanks for watching. I am going to cover more on authentication as I go in this series. I am also curious to find out the most secure way to authenticate blazor apps.
Please support the channel by subscribing and sharing :)
Hi thanks for your video, do you think its possible to implement SSO CAS Client in a blazor project?
Hello Khalid, thanks for asking the question but unfortunately I am not the right person to answer as I have very little experience in SSO CAS.
@@CuriousDrive thanks for your answer.
Its also an answer to say i don't know when you don't know ;-)
Nice tutorial! Thank you!
Thanks for watching Naveed. Please share with others :)
very helpful - thank you!
Great presentation. Thank u.
Thanks for watching Artemis. I am glad that you liked it.
Hello Can I get some help ?
I am using Blazor ServerApp,
and I am creating Custom AuthenticationStateProvider cuz I wanna authentication my Blazor App with a RESTApi , I follow the instructions in the video....
But I am getting this error:
"System.InvalidCastException: Unable to cast object of type 'Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider' to type "ApiAuthenticationStateProvider"
any help please?
Sorry for the late reply Mahmood, are you inheriting from AuthenticationStateProvider for CustomAuthenticationStateProvider? From error it seems like you are inheriting from ServerAuthenticationStateProvider.
Thanks, your videos help me a lot
Yes. It's been fun working on this series. Still working on it stay tuned!!!
Hi Fahad. Very good video. My question is can you keep the seasion even when u click another tab but when you close the browser or logout it should clear session.
Good question, in that case I would use localstorage and manually delete item on window close event from js
stackoverflow.com/q/9943220/1460321
Hello!
First of all, i really like your videos!
Blazor is new for me.
I've an question. I hope you want to help.
How do you logging in by use login.razor?
I builded exactly as your login.razor, but nothing happens when I am clicking "login" button.
I don't know where i can navigate this button to index / right place
Any idea?
Yes. I believe Index.razor would be a goof place to navigate to but it's not a hard rule.
Any page that you want home or profile page could do. Just make sure you have that component and @page on top of the component
And thanks I appreciate the comments. Please subscribe and share videos with your friends :)
@@CuriousDrive
How to do navigate this to index?
Hmm... I see that you have added a html button but I don't see that button being mapped to any C# function to navigate to the index page. You can map your Login function to @onclick event.
Or refer to this routing tutorial -> czcams.com/video/MR0uc3pJYf4/video.html
Let me know if that worked for you or not.
I solved with this Login
Thank you for getting back to me. Keep it up!
Perfect. I am glad that worked for you.
Great video and information.
I am getting this error when trying to get items from session storage:
"System.InvalidOperationException: JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendered. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method"
Can you help.
Session Storage doesn't work with Pre-rendering, any other ideas?
Yes they don't. Javascript interop does not work for pre-rendered apps. But you can change the render-mode when render your root components. Please check out the article below.
stackoverflow.com/questions/58229732/whats-the-difference-between-rendermode-server-and-rendermode-serverprerendered
You could also use cookies or what would be the disadvantage?
Have you tried to use cookies by using customstateprovider? Thanks.
Hi Kmiilo, I found a good answer for this on StackOverflow. As you make progress in this tutorial you can see that I am using token-based authentication from a third-party API that I created. Hope this helps.
stackoverflow.com/a/35059874
The real help about login...
Thanks for watching Jesús.
Excellent!
Thanks for watching Mohammed. Please share with others :)
Mant thanks for this video, very helpfull. There is still a flaw, If I add /authors to the link when on the login page I am taken to the authors page and MainLayout is displayed. How do I protect all the pages until the user is logged in?
Hey Martin, we fixed that part in the next video. Please check the link below.
czcams.com/video/PgDEpkWbsew/video.html
Hello, This one still valid to use in .NET 8? Please advise....
Nice explaination, have applied same logic for my project but due to interactive auto render mode session storage is not working in preload, can anyone guide me hot to integrate session in this case and maintain state. Already spent 8 days to looking fix for this. Need to keep preload for seo and performance.
while using child site say localhost:44391/myapp
under localhost:44391/, whenever logout action occurs its redirects to
parent site root page with 404 error, instead of login page. How to resolve this issue ?
i made the following changes in _Host.cshtml,
and configured in startup.cs,
app.UsePathBase("/myapp");
Hello Abdul, I am not completely following what you are trying to do. Is there any way that you can share your code with me. I can take a look at it and let you know my thoughts,
Great video.
I have this working locally but when I try and publish this to my website I get an error message - Entity Framework SQL Script generation failed. I don't run a SQL database on my website. How can I stop it from trying to generate a SQL script?
Hello John, Where do you exactly get that error? On login page? Is there a way I could take a look at your code?
@@CuriousDrive Sorry meant to update this. I think the problem was I started from a solution that included authentication for Individual user accounts and tried to remove the EF stuff. I recreated the project without this and got it working. I must have watched this video 10 times!! But now I know how it all works and I am happy with how it turned out. Thanks for all the work you do on this channel.
Hi.
I hope someone can help me.
I have implemented the video and in GetAuthenticationStateAsync
I am trying to use the Session State, but it fails with: InvalidOperationException: JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendered. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method.
Do you have any idea how I can solve this?
You will have to change the render-mode in _host.cshtml. Please update your component rendering to below line
@@CuriousDrive thank you very much. It worked great. I have searched all over the internet for this solution!!!
4:58 Why did you add Scoped instead of Singleton?
Singleton initializes only one instance for the whole application. That way all users will have same AuthenticationStateProvider we don't want that right?
I have explained the difference between Singleton, Transient and Scoped in the Dependency Injection episode. You can watch that one from here.
czcams.com/video/kX4oRfj1Ip8/video.html
@@CuriousDrive Why we don't want all users to have the same AuthenticationStateProvider? It access localStorage service on their local browser. And we might have only one instance. No?
@@DmitryLubenskiy Now that we are talking about it. I think it should be fine to have it as Singleton. I thought it might cause some issues when it goes in production. Let me know how it goes for you.
Could I use cookies authentication with that? Thanks.
Yes it's possible that's why IdentityServer uses. Now that I think about it I wish had done the same.
Great Job
Thanks...This one is one of my favorite demos :)
Wow! I realy like it. I looked for one for hours
Hello!
First of all, thanks for your videos!
Blazor is new for me.
I've an question. I hope you want to help.
In EP12, I follow all steps, but in minute 8:09 when execute app, la index page, show me message not authorized, and not the user name, how in your video.
I started my example with the EP12, would I be missing any other step from previous videos?
Are you running the GitHub repo? or you are running your code locally?
my own code where I'm including security
I did another test from the beginning and it works for me, it is something in the previous code of my application that does not allow security to start
I found the problem and it is this line in the startup.cs
, which I had previously added
services.AddServerSideBlazor (o => o.DetailedErrors = true);
Thank you very much for your response in a short time
thank for your vidoe. but can u use mouse to move the cursor to speed up the process?
Thanks for the feed M Z
Cool stuf.
Thanks for watching Rashad. Please share with others.
I am unable to find the code for the authentication is not uploaded in github repository.
You can't find custom authentication state provider?
Yes I can't kindly help.
There you go...
github.com/CuriousDrive/BookStores/blob/master/BlazorServerApp/BlazorServerApp/Data/CustomAuthenticationStateProvider.cs
Thanks man, great tutorial. I have two questions.
Is this Blazor Webassembly or Server-side ?
Why am I getting this error? "Unable to cast AuthenticationStateProvider to CustomAuthenticationStateProvider" error on this line of code "((CustomAuthenticationStateProvider)AuthenticationStateProvider).MarkUserAsAuthenticated(user.EmailAddress);"
Thanks in advance
Hello Pólux Rionnag, this is Blazor Server app.
Is your CustomAuthenticationStateProvider inheriting from AuthenticationStateProvider. It should be and then you won't get that error. Let me know if that does fix your issues.
@@CuriousDrive Thanks for your quick response.
Turns out that another line I needed in the Startup.cs was triggering the error, don´t know why....
services.AddServerSideBlazor().AddHubOptions(o => o.MaximumRecieveMessageSize = 102400000 );
But now it works like a charm.
Thanks again.
Hmm that's weird. People usually have to do that when they are uploading files on blazor server apps
@@CuriousDrive Yes, I was trying to do so but that mere line causes the failure.
Why tag might not to work? I have authenticate my user as you described, but in my page I see only content in , but there is an authenticated user in @content.User
Actually I found the problem. ClamIdentity must have AuthenticationType to be provided. I think this is .Net core bug.
I ran into this same error. What was your solution ?
K Jennings Hi. In my case I had to provide AuthenticationType to ClaimIdentity.
Dmitry Lubenskiy mind elaborating? I posted on stackoverflow
stackoverflow.com/questions/62921887/netcore-blazor-authentication-not-working?fbclid=IwAR1eyUKTkY-xRhWzlW3Y-MZW2WXE4GLAHeJcZBSjreKr0TAfnddoYXukOV4
@@kjennings5226 Sure. See my answer there. I hope it will help you.
Hi I am facing an issue like "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set." in login async method. Can you please suggest me to resolve this issue?
It looks like the web api is not running. You will have to setup the database and have the web api running before authenticating users.
Good tutorial, thanks! I'm interested to see how to use the WebAPI to validate the user.
Hi Morphy, I am going to record that demo today. I will let you know when it is published.
Hi Morphy, check out this demo. czcams.com/video/X6cBnOhaYhk/video.html
In my next demo I am going to make demo on IHttpClientfactory, which will make it more organized.
how to jump to the playlist from video?
Hello Alexander, I have added Blazor playlist at the end of each video of this series. Please check the link below for the playlist.
czcams.com/play/PL4WEkbdagHIR0RBe_P4bai64UDqZEbQap.html
Hi
I am getting below error
unable to cast object of type 'microsoft.aspnetcore.components.server.serverauthenticationstateprovider' to type 'blazorserver.data.customauthenticationstateprovider'.
Please help
Hello Ishita, it looks like you are trying to convert state provider which comes out of the box with the one that I am trying to build in this video. I don't think that is going to work
May I ask why are you trying to do that?
Could it be explained how to add authentication with Google in the custom login?
Thank you!
Hello Andriy, I am covering that part in the Blazor WebAssembly series. Please stay tuned for that series
czcams.com/play/PL4WEkbdagHIRjjBJvK_TSfddJSvEEAtnt.html
Simple but enough
when i referesh the page authoraztion and roles are gone,any solution pls
Have you cloned the project from GitHub? or have you typed everything and tried?
what is the difference between
@onclick="(()=>Logout())"
and
@onclick="Logout"
?
There is no difference in this case. But @onclick="(()=>Logout())" gives you options of sending EventAgrs and parameters which are set in your UI. Like this @onclick="(e => UpdateEmployee(e, employeeId))"
You can watch my event handling video here to find out more about it -
czcams.com/video/yfXQB6qwN9M/video.html
Barri, your comment was mentioned in Sunday Morning Live - czcams.com/video/XHPBmMMTXhY/video.html.
Thanks for asking awesome questions
Thank you
Thanks for watching 😊. Please share and subscribe 🙏
How to make microsoft or google login work with this custom authentication?
Hey Ahmet, There's a sample where they have shown external logins for Twitter. You can code same way for other logins too. Here's the code
github.com/dotnet-presentations/blazor-workshop
Also, I am going to show that demo in Blazor WebAssembly Series. I haven't made the episode yet but you check the 1st episode here.
czcams.com/video/v6Mt8HKAWa0/video.html
Sir in the vedio you are installing blazored sessionstorage but in the github code is for localstorage . confusion .
Yes. I changed that in between the episodes. Did not mention that in the videos. May bad!!!
Hello, Your video is really helpful as I’m implementing following your videos. But I’m stuck at one point as I’m getting an exception saying, “Unable to cast ServerAuthenticationStateProvder to CustomAuthenticationStateProvider” which you’re doing it in Login Validate Method. I would really appreciate if you can please help me on that.
Hi Tasneem, thanks for watching the videos.
I don't think you can cast your CustomAuthenticationStateProvider into ServerAuthenticationStateProvder. But it could be converted into AuthenticationStateProvder. The word "Server" is the difference.
Curious Drive Yeah right, this helped me a lot. Thank you very much..
@@CuriousDrive hey this casting is throwing some error like unable to cast so and so i followed your github code and someone raised a issue regarding the same in github.Can you please help.
@@tasneemfathima5606 Can you please let me know how did you resolve the issue ,i am also getting the same error but no where i mentioned serverAuthenticationstateprovider
I removed this code from Startup.cs , everything worked for me
services.AddServerSideBlazor().AddCircuitOptions(options => options.DetailedErrors = true );
Thank you. 👍👍👍👍👍🙏🙏🙏🙏
Why use singleton at httpclient?
I have explained the dependency injection in this video - czcams.com/video/kX4oRfj1Ip8/video.html
I did not feel the need to create scoped or transient. Do you?
I need this authentication to work with PreRendering Enabled for a SEO benefit. alas
PreRendering is good for performance but it's not good for SEO. I suggest rendering your content on the server for that.
@@CuriousDrive When u create Project with Blazor Server, Bydefault Prerendering is enabled.
Which makes HTML Content available when you check Page's Source. But when you disable PreRendering Source Code doesn't show any HTML Content. I have tested.
Hi, your code is wonderful, it explains how Authentication works, but I got the error in this line:
((CustomAuthenticationStateProvider)AuthenticationStateProvider).MarkUserAsAuthenticated(returnedUser) and the error is:
"System.InvalidCastException: Unable to cast object of type 'Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider' to type "ApiAuthenticationStateProvider", I inherit from AuthenticationStateProvider, so I couldn't figure out how does ServerAuthenticationStateProvider come?
My code has three project layers, API, Client, Service projects, API is .Net Core Web Api 5.0 and Client is Blazor-server .Net 5.0, Service is .net5.0 class library, it takes care of logic in Client, so I can create as many as client projects, and they can just call Service project, my API and Service use JWT to connect with each other. I found a comment said using services.AddServerSideBlazor().AddHubOptions(options => options.MaximumReceiveMessageSize = 102400000); but it doesn't work to me, could you please help me out?
I'm really stupid... I misplaced the services.AddScoped(); before services.AddServerSideBlazor(); so Blazor server's default AuthenticationStateProvider(which is ServerAuthenticationStateProvider) always override my custom AuthenticationStateProvider, couldn't believe I spent 5 hours without discovering it...
Is this a secure login? I´m beginner.
I would say it's secure enough to get started. Of course you can your own layers on top of it to make it more secure.
@@CuriousDrive if I validate the username and password stored in the session storages against user credentials in my database, would this make it secure?
Thank you, interesting video but quite unuseful in a real world application. Usually you need to create a user starting from some info passed via http headers from third parties authentication services (shibboleth for example). How can you access the HttpContext in order to create the user ?
HttpContext is readonly you can't modify it but you can create AuthenticationState like this -
//create a claim
var claim = new Claim(ClaimTypes.Name, currentUser.EmailAddress);
//create claimsIdentity
var claimsIdentity = new ClaimsIdentity(new[] { claim }, "serverAuth");
//create claimsPrincipal
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
return new AuthenticationState(claimsPrincipal);
Hopefully, this will be helpful
The thing is, the video is not IDENTITY, is authentication and authorization... he just created a fake user to focus on what he's explaining, in real world, you should use IDENTITY to create users, password, roles, claims, etc... then when somebody tries to log-in you search the user, check the password, etc... (IDENTITY) then if everything looks fine, you create a ClaimsPrincipal from the user and return the new AuthenticationState (AUTHENTICATION), so these things are similar but different steps...
@context shows error , pls help
solved
I am glad you solved the issue.
Cant hear a single word