Angular/Asp.Net Core Server Side Rendering for Authenticated Users
This is a follow up to “Angular/Asp.Net Core Authentication with Identity Server 4.” I’ll be using the same source code in this post.
Once you set up authentication in the Angular application, you will notice that the server side renderer no longer returns pre-rendered HTML.
This is because angular-oauth2-oidc is using browser session storage to store the OAuth token that received from the Identity Server. Therefore, the server pre-renderer can’t make authenticated HTTP requests, since session storage is not available during the server pre-rendering step. So how are we going to send the OAuth token to the server side?
By using good old Cookies!
angular-oauth2-oidc has a OAuthStorage interface that we can use to implement and define our own token storage implementation. But we need different implementations for client side and server side. This is because, even though we can access cookies directly on the client side, it is not possible to do so during server pre-rendering due to the nature of how pre-rendering works inside ASP.NET core SPA services. Could there be a way to access cookies during pre-rendering?
ASP.NET core has provided the ‘asp-prerender-data’ prop to pass any data to the server renderer function. Using that, we can retrieve the same parameter and pass it to Angular as a provider which can be resolved in any Angular service or component.
The next step is to implement the Token store service for server renderer. Here, we can resolve ‘cookies’ which contains cookies of the current request. So when the server renderer requests the OAuth token, it can be retrieved from cookies.
Finally, we need to tell Angular to use our token store implementations for OAuthStorage interface.
Once the user is authenticated from Identity server, the OAuth token should be available to the server renderer now.
Therefore, we should be able to see pre-rendered HTML during the initial loading of our application.
Complete source code can be found on GitHub.