[英]How to configure the OAuth callback to a different domain in ASP.NET Core authentication
我正在針對 OAuth 端點進行身份驗證,我只能配置 1 個回調域。 (並且 localhost 被列入白名單)。
我有我的 web 應用程序在 Azure (myapp.azurewebsites.net) 中運行,並且它可用於兩個自定義域 (myapp.cc 和 myapp.eu)。 當我使用默認設置時,CallbackPath 只能是相對路徑(到當前域)
CallbackPath
的代碼文檔表明它是相對於應用程序的基本路徑的:
/// <summary>
/// The request path within the application's base path where the user-agent will be returned.
/// The middleware will process this request when it arrives.
/// </summary>
public PathString CallbackPath { get; set; }
我想確保回調發生在我在 OAuth 后端列入白名單的(唯一)域中。 我知道我可以手動實現所有內容,但我希望有一種簡單的方法來解決這個設計問題,並且仍然可以從內置的身份驗證選項中受益。
因此,即使用戶登錄 myapp.cc 或 myapp.eu 或 myapp.azurewebsites.net,它也應重定向到 myapp.azurewebsites.net/(在我的 Auth 服務中列入白名單)
我的Startup.cs
文件的一部分粘貼在下面:
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = "MyService";
})
.AddCookie()
.AddOAuth("MyService", "MyService",
options =>
{
options.ClientId = settings.ClientId;
options.ClientSecret = settings.ClientOauthSecret;
options.CallbackPath = "/relativeonlypath";
options.SaveTokens = true;
options.SignInScheme = IdentityConstants.ExternalScheme;
/// ... removed for brevity
}
);
關於如何實現這一點的任何想法?
謝謝
我不確定這是否可能,因為要驗證用戶是否作為“真正”身份驗證流程的一部分被重定向到您的應用程序,ASP.NET OAuth 處理程序執行以下步驟:
因此,如果在步驟 #1 中為一個域(假設為myapp.cc
)生成相關 cookie,並且用戶被重定向到另一個域myapp.azurewebsites.net
, ASP.NET 核心可能無法讀取它,因為瀏覽器不會已將其包含在重定向請求中。
筆記
正如在第一條評論中看到的那樣,最初的想法是利用相關 cookie 的
SameSite
屬性讓瀏覽器將其發送到第二個域。 這都是錯誤的,道歉!
我現在認為您有兩種不同的選擇:
myapp.cc
和myapp.eu
的每個請求重定向到myapp.azurewebsites.net
,以便在身份驗證流程發生時,我們已經在正確的域中; 或者myapp.azurewebsites.net
域。我不會 go 進入第一個解決方案,因為有很多方法可以實現這一點。
下面是一些我沒有測試過的代碼,它們可能適用於第二種解決方案:
services
.AddAuthentication(options =>
{
options.DefaultChallengeScheme = "MyService";
})
.AddCookie()
.AddOAuth("MyService", options =>
{
options.Events.OnRedirectToAuthorizationEndpoint = context =>
{
var currentRequestUri = new Uri(context.Request.GetDisplayUrl());
// 1. If we're not on the correct domain, redirect the user to the same page, but on the expected domain.
// The assumption is that the authentication flow will also kick in on the other domain (see 2).
if (currentRequestUri.Host != "myapp.azurewebsites.net")
{
var applicationRedirectUri = new UriBuilder(currentRequestUri)
{
Host = "myapp.azurewebsites.net"
}.Uri.ToString();
context.Response.Redirect(applicationRedirectUri);
return Task.CompletedTask;
}
// 2. If we reach here, it means we're on the right domain, so we can redirect to the OAuth server.
context.Response.Redirect(context.RedirectUri);
return Task.CompletedTask;
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.