Windows authentication & authorization is not working in asp.net core 6 with react app

Raj 0 Reputation points
2023-11-02T13:31:41.3566667+00:00

I am developing a SPA using React with .net-core 6 template. I want to use the Windows authentication. I tried multiple ways suggested by many on the internet. It is working in build which hosted on the IIS. But not working in develoment mode.

I have created the project using this template. Screenshot 2023-11-02 173436

LaunchSettings.json

{   "iisSettings": {     "windowsAuthentication": true,     "anonymousAuthentication": true,     "iisExpress": {       "applicationUrl": "http://localhost:20344",       "sslPort": 0     }   },   "profiles": {     "StudentApp3": {       "commandName": "Project",       "launchBrowser": true,       "applicationUrl": "http://localhost:5058",       "environmentVariables": {         "ASPNETCORE_ENVIRONMENT": "Development",         "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"       }     },     "IIS Express": {       "commandName": "IISExpress",       "launchBrowser": true,       "environmentVariables": {         "ASPNETCORE_ENVIRONMENT": "Development",         "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"       }     }   } }

SetupProxy.js

const { createProxyMiddleware } = require('http-proxy-middleware');
    const { env } = require('process');    
    const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
      env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'http://localhost:20344';    
    const context =  [
        "/weatherforecast",
        "/student",
    ];    
    module.exports = function(app) {
      const appProxy = createProxyMiddleware(context, {
          target: target,
          secure: false,
      });    
      app.use(appProxy);
    };

React Fetch Call

fetch("/student/getstudent", {             method: "GET",             mode: 'cors',             credentials: 'include',             headers: {                 "Connection": 'keep-alive',             }         }).then((res) => res.json()).then((data) => {             console.log(data)             setVal(data.name)         });

Controller

using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc;  namespace StudentApp.Controllers {     [ApiController]     [Route("[controller]")]     public class StudentController : Controller     {         public IActionResult Index()         {             return View();         }          [Authorize]         [HttpGet("/student/getstudent")]         public object GetStudentName()         {             var userName = HttpContext.User?.Identity?.Name ?? "N/A";             var value = new             {                 name = "Raj"             };             return value;         }     } } 

Program.cs

using Microsoft.AspNetCore.Authentication.Negotiate;  var builder = WebApplication.CreateBuilder(args);  builder.Services.AddCors(options => {     options.AddPolicy("CORS", builder =>     {         builder             .AllowAnyHeader()                 .AllowAnyMethod()                 .AllowCredentials()                 .WithOrigins("https://localhost:44459");     }); }); builder.Services.AddControllersWithViews(); builder.Services.AddAuthentication(); builder.Services.AddAuthorization(); builder.Services.AddHttpContextAccessor();  builder.Services.AddAuthentication(options => {     options.DefaultAuthenticateScheme = NegotiateDefaults.AuthenticationScheme;     options.DefaultChallengeScheme = NegotiateDefaults.AuthenticationScheme; }).AddNegotiate();  var app = builder.Build();  // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { }  app.UseStaticFiles(); app.UseRouting();  app.UseCors("CORS");  app.UseAuthentication(); app.UseAuthorization();  app.MapControllerRoute(     name: "default",     pattern: "{controller}/{action=Index}/{id?}");  app.MapFallbackToFile("index.html"); ;  app.Run(); 
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,672 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 68,236 Reputation points
    2023-11-02T16:47:06.7266667+00:00

    the react dev proxy does not support windows authentication. you have two options

    1. switch to direct webapi api using full url and CORS.
    2. don't use the dev proxy. this requires adding a dev build to the project.json and changing .csproj to do the devbuild and not use spa url. also update any launch settings

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.