【问题标题】:Windows Authentication in .NET Core Web API / Angular application.NET Core Web API / Angular 应用程序中的 Windows 身份验证
【发布时间】:2019-11-30 12:50:49
【问题描述】:

我正在使用 Visual Studio 2019 社区构建一个 Intranet 应用程序,用于创建 .NET Core Web Api(使用 .NET Core 2.2)和用于创建 Angular 前端的 Visual Studio Code(@angular/cdk 7.1.0、@angular /cli 7.0.6,@angular/material 7.1.0)。 由于它是一个内网应用程序,我想实现 Windows 身份验证,这样用户就不必再次输入他们的凭据。 我声明我已经尝试过这个和其他论坛但没有成功,我对这些技术不是很熟悉,所以我需要帮助解决我遇到的一些问题,我可能不明白 CORS 是如何工作的。

我也尝试从邮递员调用我的 Web API(使用默认设置 =“授权:从父级继承身份验证”...),但结果相同。 我已经从 NuGet 安装了 Microsoft.AspNetCore.Cors 并实现了以下代码。

在 Web API 方面,我有这段代码。

launchSettings.json

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:62148",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebApiWinAuth": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
                services.AddCors(c =>
    {
        c.AddPolicy("AllowOrigin",
            options => options
                    .AllowAnyOrigin()
                    //.WithOrigins("http://localhost:4200")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                );
    });

    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
        .AddJsonOptions(options =>
        {
            var resolver = options.SerializerSettings.ContractResolver;
            if (resolver != null)
                (resolver as DefaultContractResolver).NamingStrategy = null;
        });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors(options => options
        .AllowAnyOrigin()
        //.WithOrigins("http://localhost:4200")
        .AllowAnyMethod()
        .AllowAnyHeader()
   );

    app.UseMvc();
}

ValuesController.cs

[Route("api/[controller]")]
[ApiController]
[Authorize]
[EnableCors("AllowOrigin")]
public class ValuesController : ControllerBase
{
    // GET api/values
    [EnableCors("AllowOrigin")]
    [HttpGet]
    [Authorize]
    public ActionResult<string> Get()
    {
        var userId = HttpContext.User.Identity.Name;
        return userId;
    }
}

在角度方面我有这个代码。

identity.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class IdentityService {

  constructor(private http:HttpClient) { }

  getCurrentUser() {

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      }),
      withCredentials: true
     };
    return this.http.get('http://localhost:62148/api/values', httpOptions)
      .toPromise();
  }
}

app.component.ts

export class AppComponent implements OnInit {
  title = 'Angular WinAuth';
  currentUser:string;

  constructor(private service: IdentityService) { }

  ngOnInit() {
    this.service.getCurrentUser().then(res => this.currentUser = res as string);
  }
}

我不断收到来自 Postman 和 Angular 应用程序的“HTTP 错误 401.2 - 未经授权”的响应。

我哪里做错了? 我应该如何实现从 Angular 到 Web Api 的调用?

如果我必须发布另一个代码,请告诉我。 提前致谢

【问题讨论】:

    标签: c# angular asp.net-core asp.net-web-api windows-authentication


    【解决方案1】:

    当我在launchSettings.json 中设置anonymousAuthentication:true 时它可以工作:

    "iisSettings": {
    "windowsAuthentication": true, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:62148",
      "sslPort": 0
    }
    

    从asp.net core中Windows AuthenticationCORS的引入,我把startup.cs改成如下:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(IISDefaults.AuthenticationScheme);//Add this line
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin",
                    options => options
                            //.AllowAnyOrigin()
                            .WithOrigins("http://localhost:4200")
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials()//Add this line
                        );
            });
    
            services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .AddJsonOptions(options =>
                {
                    var resolver = options.SerializerSettings.ContractResolver;
                    if (resolver != null)
                        (resolver as DefaultContractResolver).NamingStrategy = null;
                });
    
        }
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
    
            app.UseCors("AllowOrigin");
    
            app.UseMvc();
        }
    }
    

    【讨论】:

    【解决方案2】:

    我是 .Net Core 的新手,在使用 Windows 身份验证时遇到了类似的问题。我检查了许多帖子,但没有一个提供解决方案。使用 MVC 4 或 5 更改 applicationhost.config 解决了类似的问题。

    我发现如果我更改端口,应用程序将以调试模式启动,并且窗口身份验证将正常工作。第二次启动应用程序时,我会收到 401.1 或 401.2 错误。

    我已经转而使用 Chrome 进行开发,它似乎工作正常。这并不理想,因为我们的企业用户基于 IE 或 Edge。

    【讨论】:

      猜你喜欢
      • 2018-07-13
      • 2020-09-05
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 2017-04-27
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多