2023-03-28 22:04:56 +02:00
using System.Web ;
using AutheliaMultiDomainProxy.Backend ;
using Microsoft.AspNetCore.Mvc ;
using Microsoft.Net.Http.Headers ;
using SameSiteMode = Microsoft . AspNetCore . Http . SameSiteMode ;
namespace AutheliaMultiDomainProxy.Controllers ;
[Controller]
public class CookieProxyController : Controller {
[Produces("text/html", "text/plain")]
[Route("/api/cookieproxy_stage_one")]
2023-03-28 23:56:06 +02:00
public IActionResult StageOne ( [ FromQuery ] string tgt ) {
2023-03-28 23:12:09 +02:00
// Check if we are on the correct domain
2023-03-28 23:46:47 +02:00
if ( Request . Host . Host ! = $"{Vars.AuthProxySubdomain}.{Vars.UpstreamPrimaryDomain}" )
2023-03-28 23:12:09 +02:00
return StatusCode ( StatusCodes . Status421MisdirectedRequest ) ;
2023-03-28 23:35:38 +02:00
2023-03-28 23:56:06 +02:00
var dstDomain = AuthHelpers . GetRootDomain ( tgt ) ;
if ( ! Request . Cookies . ContainsKey ( "authelia_session" ) | | string . IsNullOrWhiteSpace ( tgt ) | | ! Vars . PermittedDomains . Contains ( dstDomain ) ) {
2023-03-28 22:04:56 +02:00
return BadRequest ( "Bad request." ) ;
}
2023-03-28 23:56:06 +02:00
var targetUrl = $"https://{Vars.AuthProxySubdomain}.{dstDomain}/api/cookieproxy_stage_two?tgt={HttpUtility.UrlEncode(tgt)}" ;
2023-03-28 23:35:38 +02:00
return
Content ( $"Redirecting to cookie proxy (stage two) on the destination domain... <form method=\" POST \ " action=\"{targetUrl}\"> <input type=\"hidden\" name=\"cookie\" value=\"{HttpUtility.HtmlEncode(Request.Cookies[" authelia_session "])}\"><button type=\"submit\">Click here</button> if you are not redirected automatically</form><script>document.querySelector(\"form\").submit();</script>" ,
"text/html" ) ;
2023-03-28 22:04:56 +02:00
}
[HttpPost]
[Produces("text/html", "text/plain")]
[Route("/api/cookieproxy_stage_two")]
2023-03-28 23:56:06 +02:00
public IActionResult StageTwo ( [ FromQuery ] string tgt , [ FromForm ] string cookie ) {
2023-03-28 23:12:09 +02:00
// Check if we are on an allowed domain
2023-03-28 23:46:47 +02:00
if ( Vars . PermittedDomains . All ( p = > Request . Host . Host ! = $"{Vars.AuthProxySubdomain}.{p}" ) )
2023-03-28 23:12:09 +02:00
return StatusCode ( StatusCodes . Status421MisdirectedRequest ) ;
2023-03-28 23:56:06 +02:00
var dstDomain = AuthHelpers . GetRootDomain ( tgt ) ;
if ( string . IsNullOrWhiteSpace ( tgt ) | | ! Vars . PermittedDomains . Contains ( dstDomain ) | | string . IsNullOrWhiteSpace ( cookie ) ) {
2023-03-28 22:04:56 +02:00
return BadRequest ( "Bad request." ) ;
}
Response . Cookies . Append ( Vars . CookieName , cookie ,
new CookieOptions {
Expires = DateTimeOffset . Now + TimeSpan . FromDays ( 365 ) ,
SameSite = SameSiteMode . Lax ,
Secure = true ,
HttpOnly = true ,
Domain = dstDomain
} ) ;
Response . Redirect ( tgt ) ;
return Content ( $"Cookie set. Redirecting... <a href=\" { tgt } \ ">Click here if you are not redirected automatically</a>" , "text/html" ) ;
}
}