.NET核心Web API/ANGING应用程序中的Windows身份验证

Windows Authentication in .NET Core Web API / Angular application(.NET核心Web API/ANGING应用程序中的Windows身份验证)
本文介绍了.NET核心Web API/ANGING应用程序中的Windows身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用用于创建.NET Core Web Api(具有.NET Core 2.2)的Visual Studio 2019社区和用于创建角度前端的Visual Studio代码(@arting/cdk 7.1.0、@arting/cli 7.0.6、@arting/Material 7.1.0)来构建一个内部网应用程序。 因为它是一个内部网应用程序,所以我想实现Windows身份验证,这样用户就不必再次输入他们的凭据。 我声明我已经尝试了这个论坛和其他论坛,但都没有成功,我不是很熟悉这些技术,所以我需要帮助来解决我遇到的一些问题,我可能不了解CORS的工作原理。 我也试着从邮递员那里调用我的Web API(默认设置="Authorization:Inherit auth from Parent"...)但结果是一样的。 我已从NuGet安装了Microsoft.AspNetCore.Cors并实现了以下代码。

在Web API端,我有以下代码。

启动Settings.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;
    }
}

在角边我有这个代码。

标识.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);
  }
}

我一直收到来自邮递员和ANGLE应用程序的"Http错误401.2-未经授权"的响应。

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

如果我必须发布另一个代码,请让我知道。 提前感谢

推荐答案

设置anonymousAuthentication:truelaunchSettings.json

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

从引入ASP.NET core中的Windows Authentication和CORS开始,我将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();
    }
}

这篇关于.NET核心Web API/ANGING应用程序中的Windows身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)