首页 > 解决方案 > Angular 使用本地 AD (Active Directory) 所以我们在 C# Web API 端获取用户

问题描述

我想通过 .net 核心 Web API 获取我们的内部 AD 用户名,以便我们可以使用它进行更改跟踪。

当我发出一个招摇请求时,这实际上有效,但是当我通过Angular 12应用程序发出相同的请求时,我得到一个 401(未经授权)

我使用了我发现的以下方法,该方法基于添加以下内容

services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();

我相信它来自此链接https://docs.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-5.0&tabs=visual-studio

我怎样才能让 Angular 传递它需要的额外细节?

目前我们只是提出这样的要求

this.http.put<IMyResponseDto>(`${this.ApiUrl}/${id}`, requestDto, { headers: this.headers });

这是 Chrome 在网络面板中向我显示的内容(如果有任何用处):

在此处输入图像描述

下面我展示了我的 .net 核心 web api 启动代码,正如我所说的那样,这在招摇中有效,但是当从角度应用程序发出相同的请求时,它似乎没有传递说明我是谁的额外重要信息?

public void ConfigureServices(IServiceCollection services)
{
    // Get the connection string from the appsettings.json
    services.AddDbContext<MyContext>(options =>
    {
        options.UseSqlServer(this.configuration.GetConnectionString("MyDatabase"));
    });

    services.AddHttpContextAccessor();
    // this allows me to get the user as an injectable object
    services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);

    services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();

    services.AddControllers();
    
    services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc(
                "v1",
                new OpenApiInfo
                    {
                        Version = "v1",
                        Title = "My API",
                        Description = "My API",
                    });
        });

    services.ConfigureSwaggerGen(c => c.CustomSchemaIds(a => a.FullName));

    services.RegisterDependencies();
}

public void Configure(IApplicationBuilder app)
{
    if (environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }
    
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "PriceBook API V1");
    });

    ConfigureCors(app);

    app.UseHttpsRedirection();
    app.UseRouting();
    
    // These have now been added
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
 

标签: c#angular.net-coreactive-directory

解决方案


推荐阅读