.NET核心Web API/ANGING应用程序中的Windows身份验证 [英] Windows Authentication in .NET Core Web API / Angular application

查看:33
本文介绍了.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 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();
    }
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆