Windows Authentication in New Dotnet SPA Templates (React + Vite)

36 views Asked by At

I am using the new ASP.NET with React template in Visual Studio, which creates two separate projects for the Server and the Client App. The template uses Vite to bundle the React application and put the scripts inside the wwwroot/Assets directory of the published package.

I am hosting my application in IIS and have been trying to implement Windows Authentication on the server side. To prevent an unauthorised user from accessing the entire application rather than just the backend API I need to authenticate when the user is trying to access the static files. Most solutions I find suggest to feed in the appropriate StaticFileOptions to the app.UseStaticFiles method in Program.cs, using the OnPrepareResponse option to redirect/reject request if the user is not authenticated. But this doesn't seem to work in this new template.

Does anyone know how to implement this with the React + Vite template? Here is the code I have been trying to use to authenticate when the user is accessing the static files.

    app.UseStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = x =>
        {
            if (x.Context.User.Identity.IsAuthenticated)
            {
                return;
            }

            x.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            x.Context.Response.ContentLength = 0;
            x.Context.Response.Body = Stream.Null;
        }
    });
0

There are 0 answers