【问题标题】:Aurelia Windows Authentication - Post 401 UnauthorizedAurelia Windows 身份验证 - 发布 401 未经授权
【发布时间】:2018-01-23 05:30:38
【问题描述】:

我完全坚持为我的一个使用 Aurelia 作为客户端的 .NET Core 应用程序实施 Windows 身份验证。

Aurelia 应用程序托管在 port:9000 上,.NET WebAPI 托管在 port:9001 上。

这个想法是在应用发布后从我的 .NET 应用中提供静态页面,但由于 Aurelia 提供的 BrowserSync,我现在正在开发中使用 port:9000

当我使用 port:9000 时,一切都很好,花花公子,我发布或获取都没有问题。

如果我切换到 port:9001,我仍然可以获取但不能发布。将结果发布到401 Unauthorized

如果我们查看 port: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 的发布(成功):

编辑 2 控制台消息发布错误:

选项http://localhost:9001/api/MYURLS 401 (Unauthorized)

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();
        }
    }

【问题讨论】:

    标签: c# .net asp.net-core aurelia windows-authentication


    【解决方案1】:

    我在项目属性中启用了“启用匿名身份验证”,瞧……

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

    部署应用程序时,无论如何都不会启用此功能,因为到那时我将使用真正的 IIS。

    更新 1

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

    services.AddAuthentication(IISDefaults.AuthenticationScheme);
    

    在您的 startup.cs 中以使其正常工作。

    更多信息可以在comment部分和docs找到。

    更新 2

    您需要 Microsoft.AspNetCore.Authentication 包用于身份验证生成器。

    【讨论】:

      【解决方案2】:

      您需要在 ASP.NET Core 项目中启用CORS。此处提供了有关如何执行此操作的信息:https://docs.microsoft.com/en-us/aspnet/core/security/cors

      您需要在ConfigureServices中拨打AddCors

      services.AddCors();
      

      然后UseCors 进入Configure

      // 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 不会有问题。我已经允许所有来源,请查看我的最新更新
      • 您是否还在IServiceCollection 上致电AddCors 并确保UseCors 高于 UseMvc
      • 也尝试了与此相同的实现:weblog.west-wind.com/posts/2016/Sep/26/…
      猜你喜欢
      • 2018-07-09
      • 1970-01-01
      • 2013-08-09
      • 2011-11-03
      • 2013-02-06
      • 2016-04-15
      • 1970-01-01
      • 2020-01-13
      • 1970-01-01
      相关资源
      最近更新 更多