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")]
public IActionResult StageOne ( [ FromQuery ] string dstDomain , [ FromQuery ] string tgt ) {
2023-03-28 23:12:09 +02:00
// Check if we are on the correct domain
if ( Request . Host . Host ! = Vars . AuthProxySubdomain + Vars . UpstreamPrimaryDomain )
return StatusCode ( StatusCodes . Status421MisdirectedRequest ) ;
2023-03-28 22:04:56 +02:00
if ( ! Request . Cookies . ContainsKey ( "authelia_session" )
| | string . IsNullOrWhiteSpace ( dstDomain )
2023-03-28 23:12:09 +02:00
| | ! Vars . PermittedDomains . Contains ( dstDomain )
2023-03-28 22:04:56 +02:00
| | string . IsNullOrWhiteSpace ( tgt ) ) {
return BadRequest ( "Bad request." ) ;
}
var targetUrl =
$"https://{Vars.AuthProxySubdomain}.{dstDomain}/api/cookieproxy_stage_two?dstDomain={HttpUtility.UrlEncode(dstDomain)}&tgt={HttpUtility.UrlEncode(tgt)}" ;
2023-03-28 23:12:09 +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")]
public IActionResult StageTwo ( [ FromQuery ] string dstDomain , [ FromQuery ] string tgt , [ FromForm ] string cookie ) {
2023-03-28 23:12:09 +02:00
// Check if we are on an allowed domain
if ( ! Request . Host . Host . StartsWith ( Vars . AuthProxySubdomain + "." ) | | ! Vars . PermittedDomains . Any ( p = > Request . Host . Host . EndsWith ( "." + p ) ) )
return StatusCode ( StatusCodes . Status421MisdirectedRequest ) ;
if ( string . IsNullOrWhiteSpace ( dstDomain ) | | ! Vars . PermittedDomains . Contains ( dstDomain ) | | string . IsNullOrWhiteSpace ( cookie ) | | string . IsNullOrWhiteSpace ( tgt ) ) {
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" ) ;
}
}