奥莉莉亚窗口身份验证 - 发送401未经授权的请求

4
我完全陷入了实现 .NET Core 应用程序的 Windows 身份验证中,该应用程序使用 Aurelia 作为客户端。Aurelia 应用程序托管在端口:9000 上,而 .NET WebAPI 托管在端口:9001 上。想法是发布应用程序后从我的 .NET 应用程序提供静态页面,但现在在开发中,由于 Aurelia 提供的 BrowserSync,我使用端口:9000。当我使用端口:9000 时,一切都很好,我没有任何问题进行发布或获取。如果我切换到端口:9001,则仍然可以获取但无法发布,发布会导致“401 未经授权”的错误。如果我们查看请求端口:9000 的标头... 可以看到,在某些情况下,发布中缺少多个标头,最重要的是身份验证 cookie。Base-Repo.js
import {inject} from 'aurelia-framework';
import {HttpClient, json} from 'aurelia-fetch-client';
import {AppSettings} from '../infrastructure/app-settings';

@inject(HttpClient, AppSettings)

export class BaseRepo {
    constructor(http, appSettings) {
        http.configure(config => {
            config
                .withDefaults({
                    credentials: 'include',
                    headers: {
                        'Accept': 'application/json'
                    }
                })
                .withInterceptor({
                    request(request) {
                        console.log(`Requesting ${request.method} ${request.url}`);
                        return request;
                    },
                    response(response) {
                        console.log(`Received ${response.status} ${response.url}`);
                        return response;
                    }
                })
        });

        this.http = http;
        this.baseUrl = appSettings.api;
    }

    get(url) {
        console.log('BaseRepo(get): ' + url);
        return this.http.fetch(this.baseUrl + url)
            .then(response => { return response.json(); })
            .then(data => { return data; });
    }

    post(url, data) {
        console.log('BaseRepo(post): ' + url, data);
        return this.http.fetch(this.baseUrl + url, {
            method: 'post',
            body: json(data)
        })
            .then(response => response.json())
            .then(data => { return data; });
    }
}

当使用BrowserSync端口时,为什么GET有效而POST无效?
编辑1
端口9001的Post(成功):
编辑2 控制台消息post错误:
OPTIONS http://localhost:9001/api/MYURLS 401 (未经授权) Fetch API无法加载http://localhost:9001/api/MYURLS。预检请求的响应未通过访问控制检查:所请求的资源上没有“Access-Control-Allow-Origin”标头。因此,不允许从源http://localhost:9000访问。响应的HTTP状态代码为401。如果不透明的响应符合您的需求,请将请求的模式设置为“no-cors”,以禁用CORS获取资源。
编辑3
Startup.cs
public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();

            env.ConfigureNLog("nlog.config");
        }

        public IConfigurationRoot Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
            });

            services.AddMemoryCache();
            services.AddMvc();

            services.InjectWebServices();

            services.AddOptions();

            //call this in case you need aspnet-user-authtype/aspnet-user-identity
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddSingleton<IConfiguration>(Configuration);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseCors("CorsPolicy");

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));

            loggerFactory.AddDebug();

            app.UseMvc();

            app.UseDefaultFiles();

            app.UseStaticFiles();

            //add NLog to ASP.NET Core
            loggerFactory.AddNLog();

            //add NLog.Web
            app.AddNLogWeb();
        }
    }
2个回答

1
您需要在ASP.NET Core项目中启用CORS。这里有关于如何实现的信息:https://learn.microsoft.com/en-us/aspnet/core/security/cors
您需要在ConfigureServices中调用AddCors
services.AddCors();

然后在Configure中使用UseCors:
// Shows UseCors with CorsPolicyBuilder.
app.UseCors(builder => builder.WithOrigins("http://example.com"));

当您使用端口9000时,与API处于不同的源,但是使用9001时,您位于相同的源上,因此CORS不适用。
OPTIONS请求称为“预检请求”。这里有更多信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

这不可能是CORS的问题。我已经允许所有来源,请查看我的最新更新。 - Reft
你是否也在 IServiceCollection 上调用了 AddCors 并确保 UseCorsUseMvc 之前 - Kirk Larkin
也尝试了与此相同的实现方式:https://weblog.west-wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas - Reft

1

enter image description here

我在项目属性中启用了“启用匿名身份验证”,然后就成功了...

之前我只启用了“启用Windows身份验证”,现在两个端口都可以使用!

当应用程序部署时,这将不会被启用,因为那时我将使用真正的IIS。

更新1

升级到 .net core 2.0 后,我不能再同时启用 Windows 身份验证和匿名身份验证。经过一些研究,我发现需要添加:

services.AddAuthentication(IISDefaults.AuthenticationScheme);

为使其正常工作,您需要在startup.cs中进行设置。

更多信息可以在评论文档部分找到。

更新2

您需要使用Microsoft.AspNetCore.Authentication包来进行身份验证构建器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接