⭐ Join Us on Patreon: www.patreon.com/CodingDroplets 🔗Blazor Tutorial Series Playlist link: ruclips.net/p/PLzewa6pjbr3IQEUfNiK2SROQC1NuKl6PV 🔗Blazor Web App Authentication: ruclips.net/video/GKvEuA80FAE/видео.html
I've completed all the parts and have successfully implemented CRUD operations and authentication with a local database, using Entity Framework. I have significantly improved. Great tutorial, many thanks!
That's fantastic to hear, and congratulations on your successful implementation of CRUD operations and authentication with a local database using Entity Framework! I'm thrilled that the tutorial was helpful in your journey to improve your skills. Keep up the great work, and happy coding! 🚀😊 .. Thank You So Much for the Support.
Absolutely the best i have seen on the web for a "how to develop a custom authentication for blazor server!". you covered all bases and that is simply awesome!
This is the best video on youtube for this topic. Explains everything from the vanilla project, and it is quick, comprehensive and to the point, and it works. On top of that, for me the explanation about server render mode in conjunction with ProtectedSessionStorage at 21:32 explained exactly the problem I'd had with other attempts to use ProtectedSessionStorage, probably from following blazor wasm tutorials, and now I know why that was. Thank you!
Very nice tutorial. You briefly showed the final product without forcing audience to wait to the end of the video. Also you did not dive into irrelevant database details, useless jokes etc. Clear and fluent narrative. Thanks!
This is the first time I see a content creator answering comments and with a deep explanation indeed. Subscribed! Of course, the video is also superb, since there are very few videos in this topic. Blessings!
Thank you so much! We're delighted to have you as part of our community. We believe in the importance of engaging with our viewers and providing thorough explanations to address any questions or concerns. Your feedback confirms that we're on the right track, and we'll continue to be responsive to our viewers' comments and provide in-depth explanations to support your learning journey.
Absolutely outstanding! This is exactly what I have been looking for! You literally took me step by step through a perfectly rendered security implementation for my Blazer Server applications. Even your variable names and coding standards were exactly how I would have implemented them. Excellent video! Thank you so much!
Yo llevaba meses buscando algo decente, y todos salían con las Razor Pages scaffoldeadas de MS Identity, incluso llegué a pensar que no se podía hacer nada si no era con eso. Fue desesperante hasta que encontré esta joya. De todos modos me preocupa el tema del render mode por lo del SEO, luego investigaré más a fondo.
Muchas gracias por ver mi video y por tu comentario! Me alegra saber que mi video ha sido útil para ti en tu búsqueda de soluciones de autenticación y autorización con Blazor Server. Es cierto que la mayoría de las soluciones que se encuentran en línea utilizan las páginas Razor Pages de MS Identity, pero hay muchas otras formas de implementar la autenticación y autorización en Blazor Server. Me complace que mi video haya sido una alternativa útil para ti.
Thank you! One of the clearer step by step tutorials I've seen on a subject I have struggled with. This is the first time I've actually understood what is going on. Appreciate that you kept the design simple and basic with clear steps. Going to follow it through using minimal API I've developed for our product, which has a JWT based auth endpoint. nb. It would be nice if you included your github code links in the summary, though I found them easily enough from your channel About page.
Thank you so much for your thoughtful feedback! Glad to hear that the step-by-step approach helped you grasp the subject more clearly and that you found the design and steps straightforward. I appreciate your suggestion regarding GitHub code links in the video summary. Providing easy access to code resources is indeed important, and I'll certainly consider your feedback for my future videos.
Great video, you helped me a lot. For those who want to recreatte this: Watch out VS sometimes suggests you code parts and the ifs are reversed e.g. instead of if(userSession != null) it suggests if(userSession == null), took me some time to realize that.
A very helpful video... I've seen many other ones and I've read some article, but this is the first time that I was able to implement a login logic, even if hard-coded data. My next step will be to use a microservice for authentication, I hope that all videos can help me as well. Regards.
Thank you for your comment and support! I'm glad to hear that the video was helpful in implementing a login logic in your Blazor Server application, even with hard-coded data. It's great to see that you were able to apply the concepts from the tutorial successfully. Using a microservice for authentication is a great next step, and I'm confident that the other videos in the series will provide valuable insights and guidance for your journey. Feel free to explore the rest of the videos, as they cover various aspects of Blazor applications. If you have any questions or need further assistance along the way, don't hesitate to reach out. Best of luck with your authentication microservice implementation, and once again thank you for your kind regards and support!
Thank you so much for taking the time to watch the video, and for your kind words! I'm glad to hear that you found the tutorial style helpful and easy to follow. I always aim to make my tutorials clear and concise, without overwhelming viewers with unnecessary information. It's great to know that this approach resonated with you and helped you to understand about this important topic. Thanks again for your feedback, and I hope you continue to find my content helpful in the future.
THANK YOU SO MUCH sir! This is exactly what I searched for. I searched through StackOverflow and I didn’t found it. I searched in other places also. You are my hero!
Thank you for your kind words and feedback! I'm glad to hear that the tutorial was exactly what you were looking for and that it helped you with your project.
Thank you for watching the video and leaving your positive feedback. I'm delighted to hear that you found my explanations to be clear and helpful in your search for a solution to your Blazor login page needs. I'm always striving to provide the best possible content to my viewers, and your comment encourages me to continue creating informative and useful videos. If you have any further questions or topics you'd like me to cover, please don't hesitate to let me know. Thanks again!
I really appreciate your clear explanations and work pace. Your tutorial provides an excellent foundation that can be easily applied to own projects :)
Thank you so much for your kind words and support, I'm thrilled to hear that you found my video helpful and consider me the GOAT (Greatest Of All Time), it means a lot to me! I appreciate you taking the time to leave a comment and for considering my content underrated, I'll continue to do my best to create more valuable videos for you and others to enjoy.
it was excellent tutorial, most of the available resource are based on the bulky aspnet tables and db context, ef core type used, but this was the actual custom authentication tutorial, thanks and great. it will be great help if added a tutorial to add custom fields in user identity , that may need to show on different pages, .i.e like full name, and other related data, like picture etc..
I'm glad to hear that you found the video helpful and that it aligned with your search for best practices! Thank you so much for your 5-star rating and positive feedback.
💥Host Your Blazor App in Linux: ruclips.net/video/bXK-F-uL7Qo/видео.html 🔗Blazor Tutorial Series Playlist link: ruclips.net/p/PLzewa6pjbr3IQEUfNiK2SROQC1NuKl6PV
Thank you for watching my video and for your question! In the GetAuthenticationStateAsync method, we need to provide the authentication type string parameter when creating the ClaimsPrincipal instance because that method is responsible for retrieving the current user's authentication information. The authentication type string specifies the type of authentication being used and is necessary to correctly create the ClaimsPrincipal instance. On the other hand, the NotifyAuthenticationStateChanged method is used to notify the application that a change in the authentication state has occurred. In this method, the authentication type string is not necessary, since it is not used to create a new ClaimsPrincipal instance. Instead, it simply notifies the application that the authentication state has changed and that the UI should be re-rendered to reflect the new state. I hope this clarifies your question. If you have further questions or need more information, please don't hesitate to let me know. Thank you again for watching my video and for your comment!
You're welcome! I'm glad that my explanation helped and that it's clear now. Thank you for watching my videos and for taking the time to leave a comment. If you have any other questions or topics you'd like me to cover, please feel free to let me know. Thanks again and have a great day!
Very cool tutorial, managed to follow all the way to the end, sometimes you go a bit too fast but it's all good. Also, I don't know if the new version of Blazor changed anything but you can't do custom NotAuthorized messages in App.Razor. I hope you can expand on this and do one when you connect to a database and then authorise other stuff like product images, profile pictures etc. I would be grateful. Stay blessed and full of luck and thanks for the knowledge!
I'm glad to hear that you found the tutorial helpful, and I appreciate your input regarding the pace of the tutorial. I'll make sure to be mindful of the pace and provide more detailed explanations in future videos. I'll definitely consider making a video addressing your queries including database connectivity.
Very well explained for someone who is new to Blazor. One question, is there a tutorial to implement 2FA as part of authentication? Or any resources that are available?
Thank you for taking the time to watch my .NET Blazor Server Authentication & Authorization video and for your kind words! As for your question regarding 2FA (Two-Factor Authentication), there are definitely resources available to help you implement it as part of your authentication flow. One resource that I recommend is the official Microsoft documentation on implementing Two-Factor Authentication in ASP.NET Core: docs.microsoft.com/en-us/aspnet/core/security/authentication/2fa?view=aspnetcore-6.0
Thank you for your kind words! I'm glad the tutorial was helpful to you. If you're using the Blazor Web App project template in .NET 8, you can refer to this video for additional insights: ruclips.net/video/GKvEuA80FAE/видео.html. Feel free to reach out if you have any further questions or need assistance. Keep up the great work, and happy coding!
This works perfectly with Net 6 and 7. Unfortunately I have tried the same thing with a .Net 8 (RTM no longer RC2) Blazor Server application and it is no longer working . I've seen that in the standart .NET 8 Blazor Web App with 'Authentication type:individual accounts', 'Interactive render mode:Server', 'Interactivity location:Per page/component' template there is a RevalidatingServerAuthenticationStateProvider instead the AuthenticationStateProvider . I have not yet figured out how this is working ! Will you update your videos for Blazor Net 8 ?
Thank you for bringing this to my attention. I appreciate your feedback. I'll make sure to explore and create updated content for Blazor Web App in .NET 8, including any changes in authentication mechanisms. Stay tuned, and I'll cover the latest developments in upcoming tutorial videos.
Thank you for this video. I have a couple of questions: 1) Why create a CustomAuthenticationProvider for Authentication instead of using CookieAuthentication? 2) Is there a way to add "Remember Me?" functionality with this?
Thank you for watching the tutorial video and for your questions! I'm glad you found the content helpful. The choice between a Custom AuthenticationStateProvider and CookieAuthentication depends on your specific requirements and preferences. While the tutorial demonstrated a custom provider for educational purposes, you can indeed use CookieAuthentication for simpler scenarios. Custom AuthenticationStateProvider can give you more control over the authentication process, including integrating with external authentication systems, such as OAuth. You can implement a "Remember Me" functionality with Blazor's authentication. When using CookieAuthentication, you can configure the expiration time of the authentication cookie to determine how long a user's session remains active.
Excellent and very help full video, can you Extend the same authentication to apply an idle timer and after a defined time say 30 Seconds user automatically logout from all the open tabs and/or windows of the same session
It can be done by providing some additional logic in GetAuthenticationStateAsync method of CustomAuthenticationStateProvider class. We'll try to do a video on this soon.
Many thanks for you, this is a very simple and straight forward lesson in blazor custom authentication and authorization. I was wondering if a user has more than one role, how to handle them, if you can do another tutorial for managing roles dynamically from the database, I mean the roles of the pages can be managed through the app not hard coded using @attribue. Highly appreciated 👍
Most welcome. I would like thank you for sharing your thoughts. For dynamic roles, we have to implement additional logics. We'll try to do a video soon.
Useful tutorial 👍👍 Thank you so much. However, how can I solve the issue where authenticated user open 2 different tabs in same browser? I noticed that the newly opened tab will not log user in.
You're most welcome! Thanks a lot for sharing your thoughts. You can make use of local storage instead of session storage. Local storage is shared between all tabs and windows from the same origin. The data does not expire. It remains after the browser restart and even OS reboot.
Thank you for your comment and I'm glad to hear that you found the tutorial helpful! Regarding your question about using a Singleton lifetime for the UserAccountService, it's important to note that in the example shown in the video, the user account details were hardcoded. However, in a real application, the user account details would typically be fetched from a database or another data source. In this scenario, using a Scoped lifetime for services that interact with a database is a good practice. Scoped lifetime means that a new instance of the service is created and shared only within the scope of a request or operation. I hope this answers your question, and if you have any further queries or concerns, please feel free to let me know!
Thank you for the great tutorial video. If I were to change it to Windows Authentication, how and where to use your CustomAuthenticationStateProvider to load all the claims for Roles from a database? Would it be the index.razor or the app.razor file? Thank you.
This video is to implement a custom authentication in a Blazor Server Application. For implementing Windows Authentication, please refer the below URL. docs.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-6.0&tabs=visual-studio
Thank you for your comment and raising a valid concern about the security and reliability of the custom AuthenticationStateProvider approach in a production application. The custom AuthenticationStateProvider demonstrated in the tutorial is a commonly used approach in Blazor Server applications and can be considered reliable and secure if implemented correctly. However, it is important to note that security is a complex topic, and there are additional factors to consider when deploying a production application. To enhance the security of your application, it is recommended to follow best practices such as: Secure Communication: Ensure that your application uses HTTPS for secure communication between the client and server. This helps protect sensitive data during transmission. Secure Password Storage: Implement proper password hashing techniques to securely store user passwords in your application's database. Input Validation: Validate and sanitize user input to prevent common security vulnerabilities like SQL injection and cross-site scripting (XSS) attacks. Authorization and Access Control: Implement proper authorization mechanisms to control user access to different parts of your application. This can involve roles, claims, or other access control techniques. Regular Updates and Security Patches: Stay updated with the latest security patches and updates for your application framework, libraries, and dependencies to address any known vulnerabilities. Remember, security is an ongoing process, and it's crucial to stay informed about the latest security best practices and techniques. Additionally, conducting thorough security testing, including penetration testing and code reviews, can help identify and address any potential vulnerabilities. By following these guidelines and adopting a proactive approach to security, you can build a production-ready application with a reliable and secure custom AuthenticationStateProvider.
Thank for this excellent tutorial and for the github code too. Do you have plan to make another video (or simple github repo) implementing localstorage (sql) , session timeout and dynamic role support? It woulde be super great! Thank you
Hi, thank you so much for your tutorial. So simple and to the point! In your github repository, I was able to get the code and tried it out. I found a commented out code //await Task.Delay(5000) Was this to remedy the issue where calling protectedsessionstorage can throw an error when used with cascading authentication state component (because JSInterlop is not initialized)? I do have this issue right now- were you able to solve it? I am wondering if I should make my own cascading authentication state component and call GetAuthenticationStateAsync manually during onAfterRenderAsync call?
Thank you for your positive feedback on the tutorial and for taking the time to try out the code from the GitHub repository. Regarding the commented out code "//await Task.Delay(5000)", its purpose was to introduce a delay for displaying a message during the authorization process. As for the JSInterop error you mentioned, in the tutorial video, we explained the option of changing the render mode to server-side rendering, which can help mitigate such issues. By utilizing server-side rendering, you can minimize the dependencies on JavaScript interop and ensure a smoother authentication process.
Thank you so much, best explanation on custom authentication!! Could you explain how to integrate an authentication from Google or from any other Authentication Provider? I would like the user to authenticate with Google, get the user's email, and then use the email to get the customer role from the database
Thank you for your comment! I'm glad to hear that you found my explanation helpful. Integrating an authentication from Google or any other Authentication Provider is definitely possible with Blazor Server App. In fact, there are built-in authentication templates available for Google, Facebook, Twitter, and Microsoft accounts. You can find more detailed instructions and code samples for integrating Google authentication in a Blazor Server App in the Microsoft documentation: docs.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins I hope this helps!
It was really a very useful tutorial. I would like to thank you for this video. Also if you could help with, how to set the session time-out value? I have been searching for this long since. Please help me.
Thanks for a great video! I'm using it in my apps now and it works really good. Now, if I'd like a user to be logged in as two separate roles at the same time, how could I do that? Right now the UserSession would be overwritten. I could append the name of the UserRole to the UserSession string name, but that wouldn't work in the GetAuthenticationStateAsync, right?
Thank you for watching the video and leaving your comment! I'm glad to hear that you found it helpful for your applications. Regarding your question, if you want to allow a user to be logged in as two separate roles at the same time, you can add multiple roles to the ClaimsPrincipal of the user.
@@CodingDroplets Thank you for your response. Normally I could, but in this scenario I have Students and Teachers, which is two different accounts. Teachers sometimes creates a Student account for testing purposes and when they log in with that account, UserSession is overwritten and they're logged out as Teacher. I hoped that I could store a UserSessionStudent and UserSessionTeacher, but I can't see how the GetAuthenticationStateAsync should handle that?
You don't need to maintain two different sessions for that. You can add multiple roles to the ClaimPrinciple. Below is an example. var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List { new Claim(ClaimTypes.Name, userSession.UserName), new Claim(ClaimTypes.Role, "Teacher"), new Claim(ClaimTypes.Role, "Student") }, "CustomAuth"));
@@CodingDroplets Thanks again! I still don't get it. There's no relation between the Teacher and Student accounts. In the morning the Teacher logs in and do his work. Later he wants to se the work from a Student perspective and logs in with a Student account. Now the Teacher-login in erased/overwritten. I could ask for the UserSession and append the role to the claims, but because it's different accounts it's not necessarily the same claims values. That's why I think I must have different UserSessions stored.
I understand your concern. In this scenario, if you want to allow the same user to be logged in with two separate roles simultaneously, then you would need to have two separate UserSessions stored, one for each role. When the Teacher logs in with their account, a Teacher UserSession is created and stored. When the Teacher logs in with the Student account, a Student UserSession is created and stored. These sessions would contain the necessary claims for each role, allowing the Teacher to switch between roles without overwriting the UserSession. To implement this, you would need to modify your authentication and authorization logic to handle multiple UserSessions and ensure that the correct session is used depending on the current role of the user.
Thank you for watching the tutorial and for your support! I'm glad you found the content helpful. Your thumbs up and subscription mean a lot to me, and they encourage me to continue creating valuable tutorials.
Thank you for your positive feedback! To prevent a user from logging into multiple instances using the same account across multiple browsers, you can implement a mechanism called "session management" or "single sign-on (SSO)". Here are a few approaches you can consider: Limit Concurrent Logins: You can restrict users to a single active session at a time. When a user logs in from a new browser, you can invalidate the previous session and force a logout. Unique Session Identifiers: Assign a unique identifier (e.g., session token) to each user session. Store these identifiers in a secure manner, such as in a database or cache. When a user attempts to log in from a different browser, you can check if the session identifier is already in use and handle the situation accordingly. Token-based Authentication: Use token-based authentication mechanisms like JSON Web Tokens (JWT). Include additional information in the token, such as the user's browser details or IP address. When a new token is issued, you can compare this information to the existing token and take appropriate action if a mismatch is detected. It's important to consider the specific requirements and security considerations of your application when implementing session management. You can explore these concepts further and adapt them to your needs.
Thank you for watching the tutorial. Glad to hear that. Yes, we do have the source code available for download on GitHub. github.com/codingdroplets/BlazorServerAuthenticationAndAuthorization
Thank you so much. It was a feature that I was looking for perfectly. I have a question, after logging in, go to the page you gave me permission and refresh (f5) and the page will be unauthenticated and the page will not be displayed (I got an error) Is there any way to solve this problem? I'd appreciate it if you could suggest a way to keep me logged in or something else even if I refresh. (.net 8.0 blazor webapp)
2 года назад+1
Hi, Thanks for your video. Just one question, is there any better way to use localstorage or cookie instead of ProtectedSessionStorage. Otherwise we lost our session in another tab.
Please check the below project in which I've used Local Storage for saving User Session details. Inside CustomAuthenticationStateProvider, you can see a constant named SESSION_VALIDITY_MINS (for Session Duration). The constant value can be changed based on your need. Also I suggest you to implement some encryption while saving the data. github.com/codingdroplets/BlazorServerAuthenticationAndAuthorizationWithLocalStorage
Thank you for this great Tutorial. I actually have three questions: First: Is this the current best practice considering an implementation for authentication? Second: Are the pasowrds hashed when stored? and third: Can multiple users be logged on at the same time or will "UserSession" in the Storage get overwritten then? Thanks in advance :)
Hi! I'd be happy to answer your questions. The use of ProtectedSessionStorage to store user session details in Blazor Server-side applications is a common practice. However, the best approach for authentication implementation depends on various factors such as the size and complexity of the application, the security requirements, and user experience. As a general rule, it is always recommended to follow industry standards and guidelines, and to consult security experts for critical applications. In the demonstration video, the passwords were not stored in a database. Instead, they were hardcoded directly into the code. It is crucial to store passwords securely by hashing and salting them before storing them in a database or any other storage medium. This helps protect user passwords in case of a data breach. This implementation allows multiple users to log in concurrently without interfering with each other's sessions. The ProtectedSessionStorage used in the tutorial is user-specific and isolated, and each user's session data is stored in their browser. Therefore, multiple users can use the application simultaneously without any conflicts. I hope this helps! Let me know if you have any further questions.
@@CodingDroplets Hello, Thank you for your fast response! Thats very good to know, about the Password hashing, is there a a function provided by Microsoft ASP which is recommended to use or do I need to implement this on my own? Thanks in advance!
You can check out this link for more information: learn.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/password-hashing This page provides a detailed explanation of how to hash passwords and also covers other topics related to password security. Hope this helps!
Great video and very informative. I wonder if you could help a little though? I have tried to implement what Milan has asked below about going straight to the login page. Which I have achieved, and when the user logs in, it takes them to the correct page, and displays the correct greeting, the problem I have is the side menu bar is "locked". If I manually enter the URL it takes me back to the login screen, which I am happy about, but can't get anywhere. Any idea as to why the sidebar is locked down?
Thank you for watching the video and leaving your comment. I'm glad to hear that you found the video informative. Regarding your question, I'm not exactly sure who Milan is or what they asked for in their comment. However, I can try to address the issue you mentioned. It seems like you have implemented a login page and the user is able to log in successfully, but the side menu bar is not working as expected. One possibility could be that you have implemented some authorization logic for the sidebar menu that prevents access until the user is authenticated. If this is the case, you may need to update your authorization logic to allow authenticated users to access the sidebar menu. I also wanted to mention that the source code for the project in the video is available on GitHub at github.com/codingdroplets/BlazorServerAuthenticationAndAuthorization. You may want to check that out to see if there are any differences between your implementation and the sample code. I hope this helps! Let me know if you have any further questions or concerns.
@@CodingDroplets thanks very much for coming back to me. I had put an else statement in my Login statement on the MainLayout page, I removed that and now I can login and use the sidebar.
Thanks for great tutorial. Just I have a question about login process and I want to know : Is this Method of custom username and password authentication secure? I mean, because in a Blazor server app, all proccessing is done server-side and on the login page, we just collect only credetials and send them to server to prove their validity. This protects sensitive data from malicious use?
Thank you for watching the tutorial and for your question. The method of custom username and password authentication shown in the tutorial is secure as long as it is implemented correctly. In the Blazor server app, all the processing is indeed done server-side and the credentials collected on the login page are sent to the server to prove their validity. This is a secure way to authenticate users and protect sensitive data from malicious use. However, it is important to note that you need to ensure that the authentication process is implemented securely and that the credentials are encrypted and stored securely on the server. I hope this answers your question. Let me know if you have any more questions or concerns.
@@CodingDroplets Thanks for your reply. Yes credentials are encrypted and stored securely on the server. My question is only about data that is collected on the login page and send to the server, and you claim that the method shown in the tutorial is secure. Did I get it right? As far as I know, this security is based on two components, ProtectedSessionStorage and AuthenticationStateProvider. Is that right?
Hii Coding Droplets I wondering if once you implements this kind of Authetication on dev you wont pay anything to put it on production(after deploy and publish the app)? Thank you
Hi there! Thanks for your comment and for watching the video. To answer your question, the authentication and authorization techniques that I covered in the video are built into Blazor Server and do not require any additional fees or services to be used in production. Once you have implemented the authentication and authorization on your development environment, you can publish your Blazor Server application to any hosting provider or server, and the authentication and authorization will continue to work as intended. However, it's important to note that the hosting providers will charge you for the hosting itself or for additional features that you may need for your application. So be sure to check the pricing and features of your hosting provider before deploying your application.
While it might seem like a lot of work to add to each page, it's a powerful and flexible approach. However, if you want a more centralized solution, you can also create a layout or a component that includes the authorization logic, and then use that layout or component across multiple pages. This way, you can manage authorization in a more centralized manner. It all depends on the structure and requirements of your application. Hope this helps!
@@CodingDroplets thank you yes I'm a bit new to Blazor and indeed to the whole Microsoft .Net Core framework (an old multivalue Pick/Revelation programmer!). Been confused over the various authentication approaches but am finding these couple of videos very useful. They take a more measured approach than some I've seen which just dive into what seem overly complex approaches.Thanks.
I believe there might be a slight misunderstanding. In the tutorial, we used "ProtectedSessionStorage" instead of "protectedsessionstate" for managing session state securely. The "ProtectedSessionStorage" is a part of Blazor's session state management system, which allows you to store and retrieve sensitive data securely in the user's session. It ensures that the data is encrypted and protected from tampering.
In the UserAccountService class if I want to populate the list with the properties of my databases, how should I approach it more or less? any ideas? Thank you
You are welcome! Just implement the method to fetch user account data from database instead of hardcoding it. If you are using SQL Server database, just make use of EF Core to achieve the same
@@anonymousug9648 - Could you please be so kind and give me here some code example how you did that? I need the same and not sure in which class/how to do that. My DB is a postgres DB. Thank you
@@CodingDropletsI am using sql server db and created a method to fetch the data from db in UserAccountService using entityframeworkcore. Will you please tell me what changes need to made in GetByUserName method
Hmm, so the built-in Identity that uses razor pages (and different layout, etc) should be replaced with blazor dedicated identity. Too bad one needs to write it again and blazor server template includes identity based on razor pages rather than blazor
Thank you for your comment and feedback on the tutorial! You're correct that when using Blazor Server, the default template includes identity based on razor pages. However, it's important to note that the decision to use the built-in Identity with razor pages or a custom authentication approach like the one demonstrated in the tutorial depends on the specific requirements and preferences of your application. The built-in Identity with razor pages provides a robust and feature-rich authentication system with pre-built UI components and functionality. If you're comfortable with razor pages and find that it meets your needs, there's no requirement to replace it with a Blazor-specific identity implementation. On the other hand, if you prefer a more customized authentication experience or want to leverage Blazor-specific features and components, implementing a custom AuthenticationStateProvider class as shown in the tutorial can be a good option. It allows you to have fine-grained control over the authentication process and integrate it seamlessly with your Blazor components.
It is possible to use old identity mechanism with roles claims etc.? I see posibilities in your code to split repository code to another project but I confiused how it can work with custom authenctitation by key.
Excellent tutorial, thank you. I am however getting the error below in program.cs (on the line 'var app = builder.Build();'). Could you please indicate how I can fix this? Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider Lifetime: Scoped ImplementationType: BlazorApp1.Authentication.CustomAuthenticationStateProvider': Unable to resolve service for type 'Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage.ProtectedBrowserStorage' while attempting to activate 'BlazorApp1.Authentication.CustomAuthenticationStateProvider'.)'
Thank You for sharing your feedback. You can find the source code of the project from the below URL. github.com/codingdroplets/BlazorServerAuthenticationAndAuthorization Please verify your source code with the demo project.
@@CodingDroplets I've cloned the source code and can confirm that it runs successfully for me. My code looks to be identical but there must be a difference somewhere - I'll keep hunting thanks!
Greetings, to those who have the error "Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider Lifetime: Scoped ImplementationType: Unable to resolve service for type 'System.Security.Claims.ClaimsPrincipal' while attempting to activate." I have a potential solution for you: In the class: "CustomAuthenticationStateProvider.cs" be sure that the "constructor" part is not expecting a parameter which you will not use. The itelliSense has put me the following: "public CustomAuthenticationStateProvider(ProtectedSessionStorage sessionStorage, ClaimsPrincipal anonymous)". This is something wrong, since it really should go: "public CustomAuthenticationStateProvider(ProtectedSessionStorage sessionStorage)". Notice that in the example number 1 I am expecting a "ClaimsPrincipal anonimous" and this is never used in the constructor, it is possible that inside the constructor the intellisense has autocompleted that code, so I recommend to copy the following code: "public CustomAuthenticationStateProvider(ProtectedSessionStorage sessionStorage)" And make that your constructor, in the class "CustomAuthenticationStateProvider.cs". It worked for me and here I leave you the comparison of my code and the tutorial. github.com/MaxwellTav/LoginAuth/commit/782295bcb29ee49add2ff2ef981e506a26200fbc Remember that to see the differences, in Github you must have the "Split" option to see the differences side by side. Best of luck.
In the context of .NET Blazor Authentication, you can include the user's ID in the authentication claims. Something like below: new Claim(ClaimTypes.NameIdentifier, userId),
unable to cast object of type Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider' to type 'CustomAuthentication.Authentication.CustomAuthenticationStateProvider here var customAuthStateProvider = (CustomAuthenticationStateProvider)asp; on the login page UI this error is showing to me what problem could be ??
Is your CustomAuthenticationStateProvider class inherited from AuthenticationStateProvider? Please find the project source code in our Github repo (URL below): github.com/codingdroplets/BlazorServerAuthenticationAndAuthorization
I followed this to a T but it has so many errors plus the variable names keep changing for the AuthStateProvider and it's CustomAuthStateProvider somewhere else
I'm sorry to hear that you encountered errors. You can find the source code for the tutorial on GitHub: github.com/codingdroplets/BlazorServerAuthenticationAndAuthorization
⭐ Join Us on Patreon: www.patreon.com/CodingDroplets
🔗Blazor Tutorial Series Playlist link:
ruclips.net/p/PLzewa6pjbr3IQEUfNiK2SROQC1NuKl6PV
🔗Blazor Web App Authentication: ruclips.net/video/GKvEuA80FAE/видео.html
I've completed all the parts and have successfully implemented CRUD operations and authentication with a local database, using Entity Framework. I have significantly improved. Great tutorial, many thanks!
That's fantastic to hear, and congratulations on your successful implementation of CRUD operations and authentication with a local database using Entity Framework! I'm thrilled that the tutorial was helpful in your journey to improve your skills. Keep up the great work, and happy coding! 🚀😊 .. Thank You So Much for the Support.
Hi, can u share the code with me I am working on authentication with local database. It will be helpful for me
Absolutely the best i have seen on the web for a "how to develop a custom authentication for blazor server!". you covered all bases and that is simply awesome!
Thank you so much for your valuable feedback. Glad to know you liked it.
This is the best video on youtube for this topic. Explains everything from the vanilla project, and it is quick, comprehensive and to the point, and it works. On top of that, for me the explanation about server render mode in conjunction with ProtectedSessionStorage at 21:32 explained exactly the problem I'd had with other attempts to use ProtectedSessionStorage, probably from following blazor wasm tutorials, and now I know why that was. Thank you!
Thank you so much for your incredibly positive feedback! Glad to hear that.
Very nice tutorial. You briefly showed the final product without forcing audience to wait to the end of the video. Also you did not dive into irrelevant database details, useless jokes etc. Clear and fluent narrative. Thanks!
You're welcome! Thank you for sharing your thoughts.
Excellent minimum Authentication Example. Straight to the topic and without any distraction.
Thank you so much for your positive feedback! Glad to hear that.
This is the first time I see a content creator answering comments and with a deep explanation indeed. Subscribed! Of course, the video is also superb, since there are very few videos in this topic. Blessings!
Thank you so much! We're delighted to have you as part of our community.
We believe in the importance of engaging with our viewers and providing thorough explanations to address any questions or concerns. Your feedback confirms that we're on the right track, and we'll continue to be responsive to our viewers' comments and provide in-depth explanations to support your learning journey.
Thanks! This was the most helpful video on this subject Thanks much
Most Welcome!!! Thanks a lot for the support.
Absolutely outstanding! This is exactly what I have been looking for! You literally took me step by step through a perfectly rendered security implementation for my Blazer Server applications. Even your variable names and coding standards were exactly how I would have implemented them. Excellent video! Thank you so much!
Thanks a lot for sharing your thoughts. I'm glad to see your comment. Once again thank you for the support.
Por fin un tutorial simple conciso, directo al punto, muchisimas gracias por el video!!!
Me alegra escuchar eso. Gracias
Yo llevaba meses buscando algo decente, y todos salían con las Razor Pages scaffoldeadas de MS Identity, incluso llegué a pensar que no se podía hacer nada si no era con eso. Fue desesperante hasta que encontré esta joya.
De todos modos me preocupa el tema del render mode por lo del SEO, luego investigaré más a fondo.
Muchas gracias por ver mi video y por tu comentario! Me alegra saber que mi video ha sido útil para ti en tu búsqueda de soluciones de autenticación y autorización con Blazor Server.
Es cierto que la mayoría de las soluciones que se encuentran en línea utilizan las páginas Razor Pages de MS Identity, pero hay muchas otras formas de implementar la autenticación y autorización en Blazor Server. Me complace que mi video haya sido una alternativa útil para ti.
@@CodingDroplets Jajaja esta respuesta parece sacada de ChatGPT.
Sí. no sé español Estoy traduciendo y respondiendo con ChatGPT. Ja ja
Thank you! One of the clearer step by step tutorials I've seen on a subject I have struggled with. This is the first time I've actually understood what is going on. Appreciate that you kept the design simple and basic with clear steps.
Going to follow it through using minimal API I've developed for our product, which has a JWT based auth endpoint.
nb. It would be nice if you included your github code links in the summary, though I found them easily enough from your channel About page.
Thank you so much for your thoughtful feedback! Glad to hear that the step-by-step approach helped you grasp the subject more clearly and that you found the design and steps straightforward.
I appreciate your suggestion regarding GitHub code links in the video summary. Providing easy access to code resources is indeed important, and I'll certainly consider your feedback for my future videos.
El mejor de lo mejor de los tutoriales que he visto, y he buscado muchos por este tema. Gracias
De nada. Me alegra escucharlo. Gracias
Great video, you helped me a lot.
For those who want to recreatte this:
Watch out VS sometimes suggests you code parts and the ifs are reversed e.g. instead of if(userSession != null) it suggests if(userSession == null), took me some time to realize that.
Thank You for sharing your thoughts.
A very helpful video... I've seen many other ones and I've read some article, but this is the first time that I was able to implement a login logic, even if hard-coded data. My next step will be to use a microservice for authentication, I hope that all videos can help me as well.
Regards.
Thank you for your comment and support! I'm glad to hear that the video was helpful in implementing a login logic in your Blazor Server application, even with hard-coded data. It's great to see that you were able to apply the concepts from the tutorial successfully.
Using a microservice for authentication is a great next step, and I'm confident that the other videos in the series will provide valuable insights and guidance for your journey. Feel free to explore the rest of the videos, as they cover various aspects of Blazor applications.
If you have any questions or need further assistance along the way, don't hesitate to reach out. Best of luck with your authentication microservice implementation, and once again thank you for your kind regards and support!
This video is amazingly concise and helpful. Thank you!!!
You're so welcome!
Great video! I love this tutorial style, no waffle or over complication. Great work, thank you.
Thank you so much for taking the time to watch the video, and for your kind words! I'm glad to hear that you found the tutorial style helpful and easy to follow.
I always aim to make my tutorials clear and concise, without overwhelming viewers with unnecessary information. It's great to know that this approach resonated with you and helped you to understand about this important topic.
Thanks again for your feedback, and I hope you continue to find my content helpful in the future.
Really useful...have been looking for something like this for a while. Well explained and clearly coded. Thanks.
Great to hear!
THANK YOU SO MUCH sir! This is exactly what I searched for. I searched through StackOverflow and I didn’t found it. I searched in other places also. You are my hero!
Thank you for your kind words and feedback! I'm glad to hear that the tutorial was exactly what you were looking for and that it helped you with your project.
Very good explanation. Thank you very much. I watched much login page on Blazor videos before this. But I found best answer at the end.
Thank you for watching the video and leaving your positive feedback. I'm delighted to hear that you found my explanations to be clear and helpful in your search for a solution to your Blazor login page needs. I'm always striving to provide the best possible content to my viewers, and your comment encourages me to continue creating informative and useful videos. If you have any further questions or topics you'd like me to cover, please don't hesitate to let me know. Thanks again!
I really appreciate your clear explanations and work pace. Your tutorial provides an excellent foundation that can be easily applied to own projects :)
Thank you so much for your wonderful comment! Glad to hear that you found our explanations clear and the tutorial's pace helpful for your learning.
Just the video that solves the problem, 100% effective! Great job!
Thank You! Glad to know it helped.
This is the best tutorial that i have ever seen.
Thank you so much for your wonderful comment! Glad to hear that.
You're the GOAT.
Thank you so much, this is really underrated!
Thank you so much for your kind words and support, I'm thrilled to hear that you found my video helpful and consider me the GOAT (Greatest Of All Time), it means a lot to me! I appreciate you taking the time to leave a comment and for considering my content underrated, I'll continue to do my best to create more valuable videos for you and others to enjoy.
Exactly what I was looking for. Thank you.
You're welcome! We're glad the tutorial met your needs.
it was excellent tutorial, most of the available resource are based on the bulky aspnet tables and db context, ef core type used, but this was the actual custom authentication tutorial, thanks and great. it will be great help if added a tutorial to add custom fields in user identity , that may need to show on different pages, .i.e like full name, and other related data, like picture etc..
Thanks a lot! Will create a video soon as you mentioned.
Best tutorial out there 100%, simple and fast
Thank You so much. Glad to know you liked it.
Very precise and well explation on blazor authentication process.
Thanks a lot.
You are most welcome
Very best practice!!! I have exactly search for this!!! 5 Stars!!!!
I'm glad to hear that you found the video helpful and that it aligned with your search for best practices! Thank you so much for your 5-star rating and positive feedback.
Great tutorial. Easy to follow and understand.
Thank you so much for taking the time to watch the tutorial video. I'm delighted to hear that you found it helpful and easy to follow.
Really Useful... Helped me get off the block with my project.
Glad it helped!
Very informative and helpful. thank you
Thank you for watching the video and leaving your comment! I'm glad to hear that you found the video informative and helpful.
💥Host Your Blazor App in Linux: ruclips.net/video/bXK-F-uL7Qo/видео.html
🔗Blazor Tutorial Series Playlist link:
ruclips.net/p/PLzewa6pjbr3IQEUfNiK2SROQC1NuKl6PV
This tutorial was exactly what I was looking for
Thanks 👍
Most welcome! Glad to know it helped.
Thank you, great tutorial to understand auth in Blazor
You're welcome. Glad to know you liked it.
Excelente, muy bien explicado paso a paso. Resulta. Gracias.
Thank You!
Very useful. I needed to do custom login and other video's were not as helpful.
Great to hear!
Great video, this perfect example helped me a lot. Thanks!
You're very welcome!
Excelente contenido, justo lo que necesitaba, muchas gracias.
Glad to know you liked it. Thanks!
just amazing video - thank you so much!
Welcome
You just saved me! haha
Great content, thank you ;)
Glad to hear it!
Why you do not provide "CustomAuth" string parameter in Update method as you did in Get method?
Thank you for watching my video and for your question! In the GetAuthenticationStateAsync method, we need to provide the authentication type string parameter when creating the ClaimsPrincipal instance because that method is responsible for retrieving the current user's authentication information. The authentication type string specifies the type of authentication being used and is necessary to correctly create the ClaimsPrincipal instance.
On the other hand, the NotifyAuthenticationStateChanged method is used to notify the application that a change in the authentication state has occurred. In this method, the authentication type string is not necessary, since it is not used to create a new ClaimsPrincipal instance. Instead, it simply notifies the application that the authentication state has changed and that the UI should be re-rendered to reflect the new state.
I hope this clarifies your question. If you have further questions or need more information, please don't hesitate to let me know. Thank you again for watching my video and for your comment!
@@CodingDroplets thank you! Now it is clear. Thank you for your videos!
You're welcome! I'm glad that my explanation helped and that it's clear now. Thank you for watching my videos and for taking the time to leave a comment. If you have any other questions or topics you'd like me to cover, please feel free to let me know. Thanks again and have a great day!
Great Expample, thank you very much!
Thank you for your kind words and I'm glad to hear that you found the video helpful!
Congratulations for video! it helped a lot! Thank you!
Glad to hear that!
Very cool tutorial, managed to follow all the way to the end, sometimes you go a bit too fast but it's all good. Also, I don't know if the new version of Blazor changed anything but you can't do custom NotAuthorized messages in App.Razor.
I hope you can expand on this and do one when you connect to a database and then authorise other stuff like product images, profile pictures etc. I would be grateful. Stay blessed and full of luck and thanks for the knowledge!
I'm glad to hear that you found the tutorial helpful, and I appreciate your input regarding the pace of the tutorial. I'll make sure to be mindful of the pace and provide more detailed explanations in future videos.
I'll definitely consider making a video addressing your queries including database connectivity.
Very well explained for someone who is new to Blazor. One question, is there a tutorial to implement 2FA as part of authentication? Or any resources that are available?
Thank you for taking the time to watch my .NET Blazor Server Authentication & Authorization video and for your kind words! As for your question regarding 2FA (Two-Factor Authentication), there are definitely resources available to help you implement it as part of your authentication flow.
One resource that I recommend is the official Microsoft documentation on implementing Two-Factor Authentication in ASP.NET Core: docs.microsoft.com/en-us/aspnet/core/security/authentication/2fa?view=aspnetcore-6.0
Dude, you are a champion! Thank you so much.
Thank you for your kind words! I'm glad the tutorial was helpful to you. If you're using the Blazor Web App project template in .NET 8, you can refer to this video for additional insights: ruclips.net/video/GKvEuA80FAE/видео.html. Feel free to reach out if you have any further questions or need assistance. Keep up the great work, and happy coding!
This works perfectly with Net 6 and 7. Unfortunately I have tried the same thing with a .Net 8 (RTM no longer RC2) Blazor Server application and it is no longer working . I've seen that in the standart .NET 8 Blazor Web App with 'Authentication type:individual accounts', 'Interactive render mode:Server', 'Interactivity location:Per page/component' template there is a RevalidatingServerAuthenticationStateProvider instead the AuthenticationStateProvider . I have not yet figured out how this is working !
Will you update your videos for Blazor Net 8 ?
Thank you for bringing this to my attention. I appreciate your feedback. I'll make sure to explore and create updated content for Blazor Web App in .NET 8, including any changes in authentication mechanisms. Stay tuned, and I'll cover the latest developments in upcoming tutorial videos.
I'm trying to figure that out too. Looks like right now there is no video or tutorial about that.
Coming soon.
@@CodingDroplets : Thank you very much
@@CodingDroplets Also looking forward to this, cant get it working with the new rendermodes, blazor just refuses to render
Great tutorial ,learned a lot.
Thank you for sharing your experience. Glad to know you liked it.
Thank you for this video. I have a couple of questions:
1) Why create a CustomAuthenticationProvider for Authentication instead of using CookieAuthentication?
2) Is there a way to add "Remember Me?" functionality with this?
Thank you for watching the tutorial video and for your questions! I'm glad you found the content helpful.
The choice between a Custom AuthenticationStateProvider and CookieAuthentication depends on your specific requirements and preferences. While the tutorial demonstrated a custom provider for educational purposes, you can indeed use CookieAuthentication for simpler scenarios. Custom AuthenticationStateProvider can give you more control over the authentication process, including integrating with external authentication systems, such as OAuth.
You can implement a "Remember Me" functionality with Blazor's authentication. When using CookieAuthentication, you can configure the expiration time of the authentication cookie to determine how long a user's session remains active.
Excellent and very help full video, can you Extend the same authentication to apply an idle timer and after a defined time say 30 Seconds user automatically logout from all the open tabs and/or windows of the same session
It can be done by providing some additional logic in GetAuthenticationStateAsync method of CustomAuthenticationStateProvider class. We'll try to do a video on this soon.
Many thanks for you, this is a very simple and straight forward lesson in blazor custom authentication and authorization.
I was wondering if a user has more than one role, how to handle them, if you can do another tutorial for managing roles dynamically from the database, I mean the roles of the pages can be managed through the app not hard coded using @attribue.
Highly appreciated 👍
Most welcome. I would like thank you for sharing your thoughts.
For dynamic roles, we have to implement additional logics. We'll try to do a video soon.
@@CodingDroplets thanks for this great video 👍 and looking forward to dynamic roles
Perfect Job! Thank you
You are most welcome!
Thank you
You're welcome
Useful tutorial 👍👍 Thank you so much. However, how can I solve the issue where authenticated user open 2 different tabs in same browser? I noticed that the newly opened tab will not log user in.
You're most welcome! Thanks a lot for sharing your thoughts.
You can make use of local storage instead of session storage. Local storage is shared between all tabs and windows from the same origin. The data does not expire. It remains after the browser restart and even OS reboot.
Thanks for the great turorial. Can you explain why you used Singleton for UserAccountService and not prefer Scoped.
Thank you for your comment and I'm glad to hear that you found the tutorial helpful! Regarding your question about using a Singleton lifetime for the UserAccountService, it's important to note that in the example shown in the video, the user account details were hardcoded. However, in a real application, the user account details would typically be fetched from a database or another data source.
In this scenario, using a Scoped lifetime for services that interact with a database is a good practice. Scoped lifetime means that a new instance of the service is created and shared only within the scope of a request or operation.
I hope this answers your question, and if you have any further queries or concerns, please feel free to let me know!
@@CodingDroplets Thank you for the prompt reply and it clarified my doubt.
Thank you for letting me know that my response was helpful and clarified your doubt!
Thank you for the great tutorial video. If I were to change it to Windows Authentication, how and where to use your CustomAuthenticationStateProvider to load all the claims for Roles from a database? Would it be the index.razor or the app.razor file? Thank you.
This video is to implement a custom authentication in a Blazor Server Application.
For implementing Windows Authentication, please refer the below URL.
docs.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-6.0&tabs=visual-studio
How reliable this is ? is this secure enough for a Production Application ?
Thank you for your comment and raising a valid concern about the security and reliability of the custom AuthenticationStateProvider approach in a production application.
The custom AuthenticationStateProvider demonstrated in the tutorial is a commonly used approach in Blazor Server applications and can be considered reliable and secure if implemented correctly. However, it is important to note that security is a complex topic, and there are additional factors to consider when deploying a production application.
To enhance the security of your application, it is recommended to follow best practices such as:
Secure Communication: Ensure that your application uses HTTPS for secure communication between the client and server. This helps protect sensitive data during transmission.
Secure Password Storage: Implement proper password hashing techniques to securely store user passwords in your application's database.
Input Validation: Validate and sanitize user input to prevent common security vulnerabilities like SQL injection and cross-site scripting (XSS) attacks.
Authorization and Access Control: Implement proper authorization mechanisms to control user access to different parts of your application. This can involve roles, claims, or other access control techniques.
Regular Updates and Security Patches: Stay updated with the latest security patches and updates for your application framework, libraries, and dependencies to address any known vulnerabilities.
Remember, security is an ongoing process, and it's crucial to stay informed about the latest security best practices and techniques. Additionally, conducting thorough security testing, including penetration testing and code reviews, can help identify and address any potential vulnerabilities.
By following these guidelines and adopting a proactive approach to security, you can build a production-ready application with a reliable and secure custom AuthenticationStateProvider.
Thank for this excellent tutorial and for the github code too. Do you have plan to make another video (or simple github repo) implementing localstorage (sql) , session timeout and dynamic role support? It woulde be super great! Thank you
Sure... Will do it soon.
Thank you for the video, well explained and simple, I would like to know if you have some video on how to work with modals to performance CRUD.
There are videos in Microservice series in which CRUD procedures are implemented. You can see the series in playlist.
Excellent thank you!!!!!
You're welcome!
Hi, thank you so much for your tutorial. So simple and to the point!
In your github repository, I was able to get the code and tried it out. I found a commented out code //await Task.Delay(5000)
Was this to remedy the issue where calling protectedsessionstorage can throw an error when used with cascading authentication state component (because JSInterlop is not initialized)? I do have this issue right now- were you able to solve it? I am wondering if I should make my own cascading authentication state component and call GetAuthenticationStateAsync manually during onAfterRenderAsync call?
Thank you for your positive feedback on the tutorial and for taking the time to try out the code from the GitHub repository. Regarding the commented out code "//await Task.Delay(5000)", its purpose was to introduce a delay for displaying a message during the authorization process.
As for the JSInterop error you mentioned, in the tutorial video, we explained the option of changing the render mode to server-side rendering, which can help mitigate such issues. By utilizing server-side rendering, you can minimize the dependencies on JavaScript interop and ensure a smoother authentication process.
amazing, Thank you, saved me, great!
Great to hear!
Thank you so much, best explanation on custom authentication!!
Could you explain how to integrate an authentication from Google or from any other Authentication Provider? I would like the user to authenticate with Google, get the user's email, and then use the email to get the customer role from the database
Thank you for your comment! I'm glad to hear that you found my explanation helpful.
Integrating an authentication from Google or any other Authentication Provider is definitely possible with Blazor Server App. In fact, there are built-in authentication templates available for Google, Facebook, Twitter, and Microsoft accounts.
You can find more detailed instructions and code samples for integrating Google authentication in a Blazor Server App in the Microsoft documentation: docs.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins
I hope this helps!
It was really a very useful tutorial. I would like to thank you for this video. Also if you could help with, how to set the session time-out value? I have been searching for this long since. Please help me.
Will do a video about it soon.
excellent video and series
Thank You!
Thanks for a great video! I'm using it in my apps now and it works really good. Now, if I'd like a user to be logged in as two separate roles at the same time, how could I do that? Right now the UserSession would be overwritten. I could append the name of the UserRole to the UserSession string name, but that wouldn't work in the GetAuthenticationStateAsync, right?
Thank you for watching the video and leaving your comment! I'm glad to hear that you found it helpful for your applications.
Regarding your question, if you want to allow a user to be logged in as two separate roles at the same time, you can add multiple roles to the ClaimsPrincipal of the user.
@@CodingDroplets Thank you for your response. Normally I could, but in this scenario I have Students and Teachers, which is two different accounts. Teachers sometimes creates a Student account for testing purposes and when they log in with that account, UserSession is overwritten and they're logged out as Teacher. I hoped that I could store a UserSessionStudent and UserSessionTeacher, but I can't see how the GetAuthenticationStateAsync should handle that?
You don't need to maintain two different sessions for that. You can add multiple roles to the ClaimPrinciple. Below is an example.
var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List
{
new Claim(ClaimTypes.Name, userSession.UserName),
new Claim(ClaimTypes.Role, "Teacher"),
new Claim(ClaimTypes.Role, "Student")
}, "CustomAuth"));
@@CodingDroplets Thanks again! I still don't get it. There's no relation between the Teacher and Student accounts. In the morning the Teacher logs in and do his work. Later he wants to se the work from a Student perspective and logs in with a Student account. Now the Teacher-login in erased/overwritten. I could ask for the UserSession and append the role to the claims, but because it's different accounts it's not necessarily the same claims values. That's why I think I must have different UserSessions stored.
I understand your concern. In this scenario, if you want to allow the same user to be logged in with two separate roles simultaneously, then you would need to have two separate UserSessions stored, one for each role.
When the Teacher logs in with their account, a Teacher UserSession is created and stored. When the Teacher logs in with the Student account, a Student UserSession is created and stored. These sessions would contain the necessary claims for each role, allowing the Teacher to switch between roles without overwriting the UserSession.
To implement this, you would need to modify your authentication and authorization logic to handle multiple UserSessions and ensure that the correct session is used depending on the current role of the user.
Thank you. Thumb & subscription done!
Thank you for watching the tutorial and for your support! I'm glad you found the content helpful. Your thumbs up and subscription mean a lot to me, and they encourage me to continue creating valuable tutorials.
Great tutorial!!! How would one prevent a user logging into multiple instances using the same account Across multiple browsers?
Thank you for your positive feedback!
To prevent a user from logging into multiple instances using the same account across multiple browsers, you can implement a mechanism called "session management" or "single sign-on (SSO)". Here are a few approaches you can consider:
Limit Concurrent Logins: You can restrict users to a single active session at a time. When a user logs in from a new browser, you can invalidate the previous session and force a logout.
Unique Session Identifiers: Assign a unique identifier (e.g., session token) to each user session. Store these identifiers in a secure manner, such as in a database or cache. When a user attempts to log in from a different browser, you can check if the session identifier is already in use and handle the situation accordingly.
Token-based Authentication: Use token-based authentication mechanisms like JSON Web Tokens (JWT). Include additional information in the token, such as the user's browser details or IP address. When a new token is issued, you can compare this information to the existing token and take appropriate action if a mismatch is detected.
It's important to consider the specific requirements and security considerations of your application when implementing session management. You can explore these concepts further and adapt them to your needs.
Perfect Video !!!!!
Thank You so much!
This is exactly what I was looking for. Thank you. Do you have the code saved somewhere to download by chance?
Thank you for watching the tutorial. Glad to hear that.
Yes, we do have the source code available for download on GitHub.
github.com/codingdroplets/BlazorServerAuthenticationAndAuthorization
@@CodingDroplets Thank you very much. I was able to take what you showed here and adapt it to my Blazor dashboard application without issues.
Thank you so much.
It was a feature that I was looking for perfectly.
I have a question, after logging in, go to the page you gave me permission and refresh (f5) and the page will be unauthenticated and the page will not be displayed (I got an error)
Is there any way to solve this problem?
I'd appreciate it if you could suggest a way to keep me logged in or something else even if I refresh.
(.net 8.0 blazor webapp)
Hi, Thanks for your video. Just one question, is there any better way to use localstorage or cookie instead of ProtectedSessionStorage. Otherwise we lost our session in another tab.
You can make use of local storage.
@codingDroplets but there is no way to use localstorage in authstateprovider in server side. Only onafterrender method allows to use it
Please check the below project in which I've used Local Storage for saving User Session details. Inside CustomAuthenticationStateProvider, you can see a constant named SESSION_VALIDITY_MINS (for Session Duration). The constant value can be changed based on your need. Also I suggest you to implement some encryption while saving the data.
github.com/codingdroplets/BlazorServerAuthenticationAndAuthorizationWithLocalStorage
This authorization information is still stored in the client, and not the server session?
Yes. Stored in the Session storage of the browser
this is the one tutorial i am searching for a long time, thanks, where i will get the source code for this
Most welcome! Glad to know you liked it. Source code available in the below link.
github.com/codingdroplets/BlazorServerAuthenticationAndAuthorization
Thank you for this great Tutorial. I actually have three questions:
First: Is this the current best practice considering an implementation for authentication?
Second: Are the pasowrds hashed when stored?
and third: Can multiple users be logged on at the same time or will "UserSession" in the Storage get overwritten then?
Thanks in advance :)
Hi! I'd be happy to answer your questions.
The use of ProtectedSessionStorage to store user session details in Blazor Server-side applications is a common practice. However, the best approach for authentication implementation depends on various factors such as the size and complexity of the application, the security requirements, and user experience. As a general rule, it is always recommended to follow industry standards and guidelines, and to consult security experts for critical applications.
In the demonstration video, the passwords were not stored in a database. Instead, they were hardcoded directly into the code. It is crucial to store passwords securely by hashing and salting them before storing them in a database or any other storage medium. This helps protect user passwords in case of a data breach.
This implementation allows multiple users to log in concurrently without interfering with each other's sessions. The ProtectedSessionStorage used in the tutorial is user-specific and isolated, and each user's session data is stored in their browser. Therefore, multiple users can use the application simultaneously without any conflicts.
I hope this helps! Let me know if you have any further questions.
@@CodingDroplets Hello, Thank you for your fast response! Thats very good to know, about the Password hashing, is there a a function provided by Microsoft ASP which is recommended to use or do I need to implement this on my own?
Thanks in advance!
You can check out this link for more information:
learn.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/password-hashing
This page provides a detailed explanation of how to hash passwords and also covers other topics related to password security. Hope this helps!
@@CodingDroplets Thank you so much for the answers! Its helps a lot!
You are welcome 🙂
Great video and very informative. I wonder if you could help a little though? I have tried to implement what Milan has asked below about going straight to the login page. Which I have achieved, and when the user logs in, it takes them to the correct page, and displays the correct greeting, the problem I have is the side menu bar is "locked". If I manually enter the URL it takes me back to the login screen, which I am happy about, but can't get anywhere. Any idea as to why the sidebar is locked down?
Thank you for watching the video and leaving your comment. I'm glad to hear that you found the video informative.
Regarding your question, I'm not exactly sure who Milan is or what they asked for in their comment. However, I can try to address the issue you mentioned. It seems like you have implemented a login page and the user is able to log in successfully, but the side menu bar is not working as expected.
One possibility could be that you have implemented some authorization logic for the sidebar menu that prevents access until the user is authenticated. If this is the case, you may need to update your authorization logic to allow authenticated users to access the sidebar menu.
I also wanted to mention that the source code for the project in the video is available on GitHub at github.com/codingdroplets/BlazorServerAuthenticationAndAuthorization. You may want to check that out to see if there are any differences between your implementation and the sample code.
I hope this helps! Let me know if you have any further questions or concerns.
@@CodingDroplets thanks very much for coming back to me. I had put an else statement in my Login statement on the MainLayout page, I removed that and now I can login and use the sidebar.
Glad to hear that you were able to resolve the issue!
Thanks for great tutorial. Just I have a question about login process and I want to know : Is this Method of custom username and password authentication secure? I mean, because in a Blazor server app, all proccessing is done server-side and on the login page, we just collect only credetials and send them to server to prove their validity. This protects sensitive data from malicious use?
Thank you for watching the tutorial and for your question. The method of custom username and password authentication shown in the tutorial is secure as long as it is implemented correctly. In the Blazor server app, all the processing is indeed done server-side and the credentials collected on the login page are sent to the server to prove their validity. This is a secure way to authenticate users and protect sensitive data from malicious use. However, it is important to note that you need to ensure that the authentication process is implemented securely and that the credentials are encrypted and stored securely on the server. I hope this answers your question. Let me know if you have any more questions or concerns.
@@CodingDroplets Thanks for your reply. Yes credentials are encrypted and stored securely on the server. My question is only about data that is collected on the login page and send to the server, and you claim that the method shown in the tutorial is secure. Did I get it right? As far as I know, this security is based on two components, ProtectedSessionStorage and AuthenticationStateProvider. Is that right?
Hii Coding Droplets I wondering if once you implements this kind of Authetication on dev you wont pay anything to put it on production(after deploy and publish the app)? Thank you
Hi there! Thanks for your comment and for watching the video.
To answer your question, the authentication and authorization techniques that I covered in the video are built into Blazor Server and do not require any additional fees or services to be used in production. Once you have implemented the authentication and authorization on your development environment, you can publish your Blazor Server application to any hosting provider or server, and the authentication and authorization will continue to work as intended.
However, it's important to note that the hosting providers will charge you for the hosting itself or for additional features that you may need for your application. So be sure to check the pricing and features of your hosting provider before deploying your application.
@@CodingDroplets thank you very much for you answer I will care about that once I get hosting. Thank u again
You are welcome
Thanks you💐💐.
You are most welcome!
Does this mean that we have to add that etc. approach in every single page (assuming they all need authorisation). Seems a lot of work?
While it might seem like a lot of work to add to each page, it's a powerful and flexible approach. However, if you want a more centralized solution, you can also create a layout or a component that includes the authorization logic, and then use that layout or component across multiple pages. This way, you can manage authorization in a more centralized manner. It all depends on the structure and requirements of your application. Hope this helps!
@@CodingDroplets thank you yes I'm a bit new to Blazor and indeed to the whole Microsoft .Net Core framework (an old multivalue Pick/Revelation programmer!). Been confused over the various authentication approaches but am finding these couple of videos very useful. They take a more measured approach than some I've seen which just dive into what seem overly complex approaches.Thanks.
That's fantastic to hear! Glad to hear that the videos are helping you.
Excellent video
Thank you very much!
Very helpful.
Glad to know it helped.
Thanks for the video.
You are most welcome
Hello,protectedsessionstate is not working in c# class could you please help me out?
I believe there might be a slight misunderstanding. In the tutorial, we used "ProtectedSessionStorage" instead of "protectedsessionstate" for managing session state securely.
The "ProtectedSessionStorage" is a part of Blazor's session state management system, which allows you to store and retrieve sensitive data securely in the user's session. It ensures that the data is encrypted and protected from tampering.
In the UserAccountService class if I want to populate the list with the properties of my databases, how should I approach it more or less? any ideas? Thank you
Good one indeed !
Thank you Mark
I want to change user account service class so that accounts get retrieved from the database
What changes do I have to make
Otherwise thanks
You are welcome! Just implement the method to fetch user account data from database instead of hardcoding it. If you are using SQL Server database, just make use of EF Core to achieve the same
@@CodingDroplets I figured it out
@@anonymousug9648 - Could you please be so kind and give me here some code example how you did that? I need the same and not sure in which class/how to do that. My DB is a postgres DB. Thank you
@@CodingDropletsI am using sql server db and created a method to fetch the data from db in UserAccountService using entityframeworkcore. Will you please tell me what changes need to made in GetByUserName method
tysm, it's working finally
You're welcome!
Hmm, so the built-in Identity that uses razor pages (and different layout, etc) should be replaced with blazor dedicated identity. Too bad one needs to write it again and blazor server template includes identity based on razor pages rather than blazor
Thank you for your comment and feedback on the tutorial! You're correct that when using Blazor Server, the default template includes identity based on razor pages. However, it's important to note that the decision to use the built-in Identity with razor pages or a custom authentication approach like the one demonstrated in the tutorial depends on the specific requirements and preferences of your application.
The built-in Identity with razor pages provides a robust and feature-rich authentication system with pre-built UI components and functionality. If you're comfortable with razor pages and find that it meets your needs, there's no requirement to replace it with a Blazor-specific identity implementation.
On the other hand, if you prefer a more customized authentication experience or want to leverage Blazor-specific features and components, implementing a custom AuthenticationStateProvider class as shown in the tutorial can be a good option. It allows you to have fine-grained control over the authentication process and integrate it seamlessly with your Blazor components.
It is possible to use old identity mechanism with roles claims etc.?
I see posibilities in your code to split repository code to another project but I confiused how it can work with custom authenctitation by key.
Excellent tutorial, thank you. I am however getting the error below in program.cs (on the line 'var app = builder.Build();'). Could you please indicate how I can fix this?
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider Lifetime: Scoped ImplementationType: BlazorApp1.Authentication.CustomAuthenticationStateProvider': Unable to resolve service for type 'Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage.ProtectedBrowserStorage' while attempting to activate 'BlazorApp1.Authentication.CustomAuthenticationStateProvider'.)'
Thank You for sharing your feedback. You can find the source code of the project from the below URL.
github.com/codingdroplets/BlazorServerAuthenticationAndAuthorization
Please verify your source code with the demo project.
@@CodingDroplets I've cloned the source code and can confirm that it runs successfully for me. My code looks to be identical but there must be a difference somewhere - I'll keep hunting thanks!
Greetings, to those who have the error "Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider Lifetime: Scoped ImplementationType: Unable to resolve service for type 'System.Security.Claims.ClaimsPrincipal' while attempting to activate."
I have a potential solution for you:
In the class: "CustomAuthenticationStateProvider.cs" be sure that the "constructor" part is not expecting a parameter which you will not use.
The itelliSense has put me the following:
"public CustomAuthenticationStateProvider(ProtectedSessionStorage sessionStorage, ClaimsPrincipal anonymous)".
This is something wrong, since it really should go:
"public CustomAuthenticationStateProvider(ProtectedSessionStorage sessionStorage)".
Notice that in the example number 1 I am expecting a "ClaimsPrincipal anonimous" and this is never used in the constructor, it is possible that inside the constructor the intellisense has autocompleted that code, so I recommend to copy the following code:
"public CustomAuthenticationStateProvider(ProtectedSessionStorage sessionStorage)"
And make that your constructor, in the class "CustomAuthenticationStateProvider.cs".
It worked for me and here I leave you the comparison of my code and the tutorial.
github.com/MaxwellTav/LoginAuth/commit/782295bcb29ee49add2ff2ef981e506a26200fbc
Remember that to see the differences, in Github you must have the "Split" option to see the differences side by side.
Best of luck.
great vid. ty
Most welcome!
Protected Session Storage is now deprecated. What else can we use instead?? I saw Blazored is it fine?
Yes.. You can use Blazored
thank you so much
You are welcome!
big thanks!!
Most welcome
Hey, is it also possible to add an id to the session?
In the context of .NET Blazor Authentication, you can include the user's ID in the authentication claims. Something like below:
new Claim(ClaimTypes.NameIdentifier, userId),
okay thanks. Subscribed!
Thank you ❤
You're welcome 😊
unable to cast object of type
Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider' to type 'CustomAuthentication.Authentication.CustomAuthenticationStateProvider
here
var customAuthStateProvider = (CustomAuthenticationStateProvider)asp; on the login page UI
this error is showing to me what problem could be ??
Is your CustomAuthenticationStateProvider class inherited from AuthenticationStateProvider? Please find the project source code in our Github repo (URL below):
github.com/codingdroplets/BlazorServerAuthenticationAndAuthorization
@@CodingDroplets ye same as you code
Its working Thank you..
@@CodingDroplets drop repo link in description. very nice explanation .
@@Kiran.KillStreak github.com/codingdroplets/BlazorServerAuthenticationAndAuthorization
Thank you !! :D
You're welcome!
I followed this to a T but it has so many errors plus the variable names keep changing for the AuthStateProvider and it's CustomAuthStateProvider somewhere else
I'm sorry to hear that you encountered errors. You can find the source code for the tutorial on GitHub: github.com/codingdroplets/BlazorServerAuthenticationAndAuthorization