Windows 身份验证和授权在带有 react 应用程序的 asp.net core 6 中不起作用

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

提问人:Raj 提问时间:11/2/2023 最后编辑:Raj 更新时间:11/2/2023 访问量:45

问:

我正在使用带有 .net-core 6 模板的 React 开发 SPA。我想使用 Windows 身份验证。我尝试了互联网上许多人建议的多种方法。它正在 IIS 上托管的构建中工作。但不能在开发模式下工作。

我使用此模板创建了项目。点击打开

  1. LauncSettings.json 点击打开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"
          }
        }
      }
    }
  1. SetupProxy.js 单击以打开 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);
    };
  1. React Fetch Call 点击打开 Fetch call from react
    fetch("/student/getstudent", {
                method: "GET",
                mode: 'cors',
                credentials: 'include',
                headers: {
                    "Connection": 'keep-alive',
                }
            }).then((res) => res.json()).then((data) => {
                console.log(data)
            });
  1. 控制器 点击打开控制器
    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;
            }
        }
    }
  1. 程序 .cs 单击以打开程序 .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();

我很欣赏你们的解决方案。 提前致谢

我尝试了多种方法,但没有一种帮助。

reactjs .net-core windows 身份验证

评论

2赞 akseli 11/2/2023
请在您的问题中包含您的代码片段作为代码片段,并避免使用图像。
0赞 possum 11/2/2023
这是不可接受的提问方式。在此处以文本形式发布您的代码
0赞 Raj 11/2/2023
@akseli 对不起,我是新手。现在我添加了代码片段。请为此提供一些解决方法。谢谢。
0赞 Raj 11/2/2023
@possum对不起,伙计,现在我添加了它。请就此提出一些建议。谢谢。

答: 暂无答案