我正在使用 IdentityServer 4 通过外部登录提供商 (Microsoft) 为我的 Web 应用程序提供身份验证和自动授权。
当我在本地运行 IdentityServer 和我的 Web 应用程序时,这工作得很好。但是,当我将 Identityserver 项目发布到 Azure 时,它不再起作用。
当我将本地运行的 Web 应用程序连接到已发布的 IdentityServer 时,从 Microsoft 登录页面返回后,该 Web 应用程序失败并显示错误“关联失败”。未知地点”。
Web 应用程序的输出显示:
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler:
Warning: '.AspNetCore.Correlation.oidc.xxxxxxxxxxxxxxxxxxx' cookie not found.
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler:
Information: Error from RemoteAuthentication: Correlation failed..
Run Code Online (Sandbox Code Playgroud)
但是,当我检查浏览器时,确实存在一个名称为“.AspNetCore.Correlation.oidc.xxxxxxxxxxxxxxxxxxx”的 cookie。
这是网络应用程序中的startup.cs:
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 …Run Code Online (Sandbox Code Playgroud) 我只是没有运气将 url 编码的表单值从邮递员发送到使用文件-> 新项目创建的 vanilla asp.net core 2.1 web api。我什么也没做,但新的模型验证功能似乎仍然启动并向邮递员返回 400 Bad Request。谁能告诉我我做错了什么?
控制器动作:
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
Run Code Online (Sandbox Code Playgroud)
原始请求(如 fiddler 所示):
POST http://localhost:60843/api/values HTTP/1.1
Content-Type: application/x-www-form-urlencoded
cache-control: no-cache
Postman-Token: a791eee7-63ff-4106-926f-2s67a8dcf37f
User-Agent: PostmanRuntime/7.3.0
Accept: */*
Host: localhost:60843
accept-encoding: gzip, deflate
content-length: 7
Connection: keep-alive
value=test
Run Code Online (Sandbox Code Playgroud)
原始回复:
HTTP/1.1 400 Bad Request
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
X-SourceFiles: =?UTF-8?BQzpcUmVwb3NcVGVzdGJlZFxNb2RlbEJpbmRpbmdcTW9kZWxCaW5kaW5nXGFwaVx2YWx1ZXM=?=
X-Powered-By: ASP.NET
Date: Thu, 25 Oct 2018 15:23:49 GMT
21
{"":["The input was not valid."]} …Run Code Online (Sandbox Code Playgroud) 当我发布 ASP.NET MVC Core 3.1 应用程序时,异常日志包含开发人员计算机的路径。
日志示例:
2021-04-27 16:36:47.1954 | |18f76390-4123opr9fjnfe832. | ERROR | Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware | An unhandled exception has occurred while executing the request. | System.Exception: TEST
at ClassLibrary.Repositories.HomeRepo.GetSummary() in C:\Users\FLASTNAME\TFS\dotnet\APPNAME\.......:line 68
at ClassLibrary.Services.HomeService.GetStatuses() in C:\Users\FLASTNAME\TFS\dotnet\APPNAME\.......:line 38
at Project.Controllers.HomeController.GetSummary() in C:\Users\FLASTNAME\TFS\dotnet\APPNAME\.......\HomeController.cs:line 39
at lambda_method(Closure , Object )
at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
......
......
Run Code Online (Sandbox Code Playgroud)
行号和文件位置对于识别错误原因很有用,但路径包含开发人员的名称FLASTNAME,如果不存在的话我更希望如此。
我的研究最接近的是 .pdb 文件(1 , 2),一些建议更改构建设置中的调试信息:
但是,我尝试了每个选项,但它仍然显示完整路径。我无法选择在另一台机器上构建项目,那么在这种情况下我该怎么办?
我知道我可能在这里误解了一些东西,但即使在Release配置中构建项目也不能解决我的问题。
编辑:
<PathMap>这是@Kirk Larkin 建议添加代码的结果
<PropertyGroup>
<PathMap>$(MSBuildProjectDirectory)=ANOTHERPATH</PathMap>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)
到项目的 csproj 文件:
2021-04-27 16:36:47.1954 | …Run Code Online (Sandbox Code Playgroud) 我想创建和端点符合“JSON Merge Patch” https://tools.ietf.org/html/rfc7396
请不要将它与“JavaScript Object Notation (JSON) Patch”混淆 https://tools.ietf.org/html/rfc6902
但是,我在区分请求中的两种情况时遇到了一个小问题:
删除属性值,这里正在删除电子邮件值:
{
surname: "Kowalski"
email: null
}
Run Code Online (Sandbox Code Playgroud)属性不包括,因为客户根本不想更新它,这里不包括电子邮件,因为它不应该更新:
{
surname: "Kowalski"
}
Run Code Online (Sandbox Code Playgroud)出现问题是因为在模型绑定后的两种情况下,电子邮件的值为 null。
你有什么建议吗?
我使用以下组合来实现这一点:1) 浏览器隐身模式 (Chrome) 2) 应用程序位于 Azure 应用程序网关后面(如果不是,则不进行复制)。关闭基于 Cookie 的关联(默认);如果打开,似乎会使重现更频繁地发生。
代码是相当普通的 OIDC authN + cookie。
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddAzureAd(options => {
Configuration.Bind("AzureAd", options);
})
.AddCookie(p => p.SlidingExpiration = true);
Run Code Online (Sandbox Code Playgroud)
我按照建议将 X-Forwarded-Proto 标头转发到 auth 中间件,以便 redirect_uri 使用正确的协议方案。
代码处理
我尝试处理OnRemoteFailure()事件,并重定向到“/Home/AuthRedirect”,这是一个等待 20 秒的匿名页面,然后重定向到“/”(主页)。它有时似乎有效,但并非总是如此。我没有想法。
变通方法
1) 用户可以再次进入主页并按 F5 直到这有效。似乎每个 F5 都让他们向前迈进了一步,一旦填充了 OpenID cookie,其他一切(在 openid 完成后我有更多的身份验证,通过 adal.js 用于 AJAX 使用)。2) 绕过应用程序网关并使用直接服务结构集群 DNS 名称(不接受,因为它是 http)。
细节
System.Exception:关联失败。在 Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.d__12.MoveNext() --- 从上一个抛出异常的位置的堆栈跟踪结束 --- 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Runtime。 CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at …
c# asp.net-identity openid-connect asp.net-core azure-application-gateway
我有两种方法来处理 HTTP GET 请求,第一种用于int类型输入,另一种用于string类型输入。
//GET : api/Fighters/5
[HttpGet("{id}")]
public async Task<ActionResult<Fighter>> GetFighter(int id)
{
var fighter = await _context.Fighters.FindAsync(id);
if (fighter == null)
{
return NotFound();
}
return fighter;
}
// GET: api/Fighters/Alex
[Route("api/Fighters/{name}")]
[HttpGet("{name}")]
public async Task<ActionResult<IEnumerable<Fighter>>> GetFighter (string name)
{
return await _context.Fighters.Where(f => f.Name == name).ToListAsync();
}
Run Code Online (Sandbox Code Playgroud)
当我发送 HTTP GET 时出现此异常(在 Postman 中):
Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints. Matches:
FighterGameService.Controllers.FightersController.GetFighter (FighterGameService)
FighterGameService.Controllers.FightersController.GetFighter (FighterGameService)
FighterGameService.Controllers.FightersController.GetFighter (FighterGameService)
FighterGameService.Controllers.FightersController.GetFighter (FighterGameService)
at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ReportAmbiguity(CandidateState[] candidateState)
at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ProcessFinalCandidates(HttpContext …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 .NET Core 3.1 中开发一个项目。我正在尝试在我的项目中实现基于 cookie 的身份验证。我的登录功能是:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(UserLoginModel userModel)
{
if (!ModelState.IsValid)
{
return View(userModel);
}
if (userModel.Email == "admin@test.com" && userModel.Password == "123")
{
var identity = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "User Id"));
identity.AddClaim(new Claim(ClaimTypes.Name, "User Name"));
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal);
return RedirectToAction(nameof(HomeController.Index), "Home");
}
else
{
ModelState.AddModelError("", "Invalid UserName or Password");
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
为了实现基于 cookie 的身份验证,我将以下代码放入 Startup 类的 ConfigureService 方法中:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.Configure<CookiePolicyOptions>(options …Run Code Online (Sandbox Code Playgroud) 我想构建一个基于 ASP.NET Core 的 WebApi 用于从数据库访问数据。该 WebApi 可以通过两种方式使用,要么作为需要身份验证的公共 WebApi,要么作为 Web 应用程序的私有后端服务。在后一种情况下,不需要身份验证,因为只有经过身份验证的用户才能访问 Web 应用程序,并且 Web 应用程序和 WebApi 将在同一台计算机上运行,WebApi 将向外部隐藏。
由于我们需要对第一个场景进行身份验证,因此我将使用 Authorize 属性标记所有公共 API。但对于私人场景,我想绕过任何身份验证。
有什么方法可以根据配置中的某些标志使身份验证可选?
更新
说到两种使用场景,我的意思是两个完全独立的安装!每个都有自己的配置文件。是否需要身份验证的决定是根据安装而不是根据单个安装中的请求做出的!我的目标是在配置中只有一个代码库和一个开关。
我正在设置社交登录提供程序身份验证,无需使用 Microsoft 身份验证的 ASP.NET Core Identity。链接的教程使用 Google 作为示例,并提供了获取其身份验证方案的代码DefaultChallengeScheme。
Microsoft 的身份验证方案是什么?我一直找不到它。
我的 Startup.cs > ConfigureServices 方法:
public void ConfigureServices(IServiceCollection services)
{
//set up using this tutorial https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/social-without-identity?view=aspnetcore-2.2
services
.AddAuthentication(authenticationOptions =>
{
authenticationOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
authenticationOptions.DefaultChallengeScheme = //??? what goes here
})
.AddCookie()
.AddMicrosoftAccount(microsoftOptions =>
{
microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ClientId"];
microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"];
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
Run Code Online (Sandbox Code Playgroud) 我们有一个 NET Core 3.1 Web 应用程序,其中用户使用Microsoft.Identity.Web包在 Azure AD 中进行身份验证。我们将代表登录用户调用 Microsoft Graph SDK,如此处所述。
登录到应用程序后,一切正常 - 对 Microsoft Graph SDK 的所有调用均成功。但是,大约 30-60 分钟后(我们没有准确计时),用户在我们的应用程序中保持身份验证,但对 Microsoft Graph SDK 的调用失败,并出现以下错误:
IDW10502: An MsalUiRequiredException was thrown due to a challenge for the user.
Run Code Online (Sandbox Code Playgroud)
内部异常有:
Microsoft.Identity.Client.MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call.
Run Code Online (Sandbox Code Playgroud)
然后,用户需要注销应用程序并重新登录,之后对 MS Graph 的调用在 30-60 分钟内再次成功。
任何人都可以阐明这一点吗?
我们的设置
在 appsettings.json 中:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "<our-domain-name>",
"TenantId": "<our-tenant-id>",
"ClientId": "<our-client-id>",
"CallbackPath": "/signin-oidc",
"SignedOutCallbackPath ": …Run Code Online (Sandbox Code Playgroud) c# azure asp.net-core microsoft-graph-sdks microsoft-identity-platform
asp.net-core ×10
c# ×10
api-design ×1
asp.net ×1
asp.net-mvc ×1
azure ×1
build ×1
microsoft-identity-platform ×1
pdb-files ×1
rest ×1