我正在使用 Visual Studio 2019 Community 构建一个 Intranet 应用程序,用于创建 .NET Core Web Api(使用 .NET Core 2.2),并使用 Visual Studio Code 来创建 Angular 前端(@angular/cdk 7.1.0、@angular/cli 7.0 .6,@角度/材料7.1.0)。
由于它是一个 Intranet 应用程序,我想实现 Windows 身份验证,以便用户不必再次输入其凭据。
我声明我已经尝试过这个和其他论坛但没有成功,我对这些技术不是很熟悉,所以我需要帮助来解决我遇到的一些问题,我可能不明白 CORS 是如何工作的。
我也尝试从邮递员调用我的 Web API(默认设置=“授权:从父级继承身份验证”...),但结果相同。
我已经从 NuGet 安装了 Microsoft.AspNetCore.Cors 并实现了以下代码。
在 Web API 方面,我有这段代码。
启动设置.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"
}
}
}
}
启动.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;
}
}
在有角度的一侧我有这个代码。
身份.服务.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();
}
}
应用程序组件.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的调用?
如果我需要发布另一个代码,请告诉我。
提前致谢