![](/img/trans.png)
[英]Authentication with Azure Active Directory connected services missing in existing Asp.Net core application
[英]Why is Azure Active Directory Authentication causing an character encoding error in my ASP.NET Core Application?
我有一个正在制作的ASP.NET Core 2.2应用程序,它使用KendoUI作为其框架的一部分。 我最近设置了应用程序的骨骼,然后使用Visual Studio 2019的内置向导添加了Azure Active Directory身份验证。 这在Azure中为我创建了一个应用程序注册,该注册将根据我公司的活动目录对用户进行身份验证。
问题是,当我现在运行我的应用程序时,出现以下错误并且没有页面加载:
未声明纯文本文档的字符编码。 如果文档包含来自US-ASCII范围之外的字符,则在某些浏览器配置中,文档将呈现乱码。 需要在传输协议中声明文件的字符编码,或者文件需要使用字节顺序标记作为编码签名。
对该消息的进一步调查显示了更多详细信息,这些细节是:
加载此URI时出错:协议错误(unknownError):无法为https:// localhost:44379 /加载源。 [异常...“组件返回的失败代码:0x80470002(NS_BASE_STREAM_CLOSED)[nsIInputStream.available]” nsresult:“ 0x80470002(NS_BASE_STREAM_CLOSED)”“位置:” JS框架:: resource://devtools/shared/DevToolsUtils.js :: onResponse ::“ 555行”数据:否]堆栈:onResponse @ resource://devtools/shared/DevToolsUtils.js:555:34 onStopRequest @ resource://gre/modules/NetUtil.jsm:123:17行:555,列:0
我查看了添加AAD期间受影响的所有内容,并且项目中的以下文件已更改。
[Authorise]
放置在HomeController.cs
之前在我的应用程序中使用过AAD之后,我希望看到这些文件已更改,但是以后运行该应用程序时我从未遇到任何问题。 我开始研究可能引起问题的更改。 经过一些工作后,我意识到,如果我从控制器中删除[Authorize]
,则一切正常。
我猜这可能是我的应用程序注册中潜在的路由问题? 我不确定,我需要一些帮助,因为该消息有点像是红色鲱鱼,因为它表明存在HTML格式问题。 对于发生了什么问题,我需要一些指导。
这是我的代码和项目结构。
结构体
我总是将UI与类库分开,因为AAD不会更改Data,Repo或Services库中的文件,为简洁起见,我不会在此问题中包括它们。
MyCompany.UI / Controllers / HomeController.cs
using MyCompany.Data;
using Kendo.Mvc.UI;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using MyCompany.Services;
using Kendo.Mvc.Extensions;
using Microsoft.AspNetCore.Authorization;
namespace MyCompany.Controllers
{
[Authorize]
public class HomeController : Controller
{
private readonly IVesselService _service;
public HomeController(IVesselService vesselService)
{
_service = vesselService;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
public ActionResult ReadVessels([DataSourceRequest]DataSourceRequest request)
{
var vessel = _service.GetVessels();
return Json(vessel.ToDataSourceResult(request));
}
[AcceptVerbs("Post")]
public ActionResult CreateVessel([DataSourceRequest] DataSourceRequest request, Vessel vessel)
{
if (vessel != null && ModelState.IsValid)
{
_service.InsertVessel(vessel);
}
return Json(new[] { vessel }.ToDataSourceResult(request, ModelState));
}
[AcceptVerbs("Post")]
public ActionResult UpdateVessel([DataSourceRequest] DataSourceRequest request, Vessel vessel)
{
if (vessel != null && ModelState.IsValid)
{
_service.UpdateVessel(vessel);
}
return Json(new[] { vessel }.ToDataSourceResult(request, ModelState));
}
[AcceptVerbs("Post")]
public ActionResult DestroyVessel([DataSourceRequest] DataSourceRequest request, Vessel vessel)
{
if (vessel != null)
{
_service.DeleteVessel(vessel.Id);
}
return Json(new[] { vessel }.ToDataSourceResult(request, ModelState));
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
MyCompany.UI / Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Serialization;
using MyCompany.Repo;
using Microsoft.EntityFrameworkCore;
using MyCompany.Services;
namespace MyCompany
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
// Maintain property names during serialization. See:
// https://github.com/aspnet/Announcements/issues/194
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
// Database Context
services.AddDbContext<MyCompanyContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyCompanyConnection"), b => b.MigrationsAssembly("MyCompany.Repo")));
//Repository Scope
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
services.AddTransient<IVesselService, VesselService>();
//Azure AD Authentication
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddAzureAdBearer(options => Configuration.Bind("AzureAd", options));
//Add KendoUI Services to services container
services.AddKendo();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// 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.UseHttpsRedirection();
app.UseCookiePolicy();
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
MyCompany / appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Warning",
"System": "Information",
"Microsoft": "Information"
}
},
"ConnectionStrings": {
"MyCompanyConnection": "Server=tcp:mydatabase.database.windows.net,0000;Initial Catalog=MyDatabase;Persist Security Info=False;User ID=Cloud;Password=Midgar1997!;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
},
"AllowedHosts": "*",
"AzureAd": {
"ClientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"Domain": "mycompany.onmicrosoft.com",
"Instance": "https://login.microsoftonline.com/",
"TenantId": "xxxxxxxx",
"CallbackPath": "/signin-oidc",
"ClientSecret": "xxxxxx",
"AppIDURL": "https://mycompany.onmicrosoft.com/MyCompany.UI",
"ConfigView": "MVC"
}
}
因此,这是与AAD直接相关的代码,我不确定这是路由问题还是应用注册的不正确配置。 我需要一些帮助。
如果您可以重现此错误,则可以将其作为产品错误报告给AAD团队。 如果您要连接到其他服务(例如Azure SQL)并且连接存在问题,有时会发生此错误。 您是否还有其他错误日志?
如果您想获得支持票,请随时通过AzCommunity@microsoft.com与我联系,我可以为您开箱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.