title: Authenticate CORS request using OpenIdConnect and Azure AD
body: <p>I have Asp.Net core backend running in Azure.
  HTML/JS frontend running on localhost, using CORS to communicate with backend</p>
  
  <p>When both, frontend and backend are in localhost, or they are both in Azure, the authentication works -> Azure AD app is setup correctly. </p>
  
  <p>Here is how I log in:</p>
  
  <pre><code>[Route("/api/[controller]")]
  public class AccountController : Controller
  {
      [HttpGet]
      public IActionResult Index()
      {        
          return Json(new AccountInfoViewModel
          {
              IsAuthenticated = User.Identity.IsAuthenticated,
              UserName = User.Identity.Name,
              Roles = new string[0],
              LoginUrl = Url.Action(nameof(Login), null, null, null, Request.Host.Value),
              LogoutUrl = Url.Action(nameof(Login), null, null, null, Request.Host.Value),
          });
      }
  
      [HttpGet("login")]
      public async Task Login(string returnUrl)
      {
          await HttpContext.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = returnUrl });
      }
  
      [HttpGet("logoff")]
      public async Task LogOff()
      {
          await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
          await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
      }
  
      [HttpGet("endsession")]
      public async Task EndSession()
      {
          // If AAD sends a single sign-out message to the app, end the user's session, but don't redirect to AAD for sign out.
          await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
      }
  }
  </code></pre>
  
  <p>so from localhost, I then redirect to:</p>
  
  <pre><code>https://myapp.azurewebsites.net/Account/Login?returnUrl=localhost:12345
  </code></pre>
  
  <p>which triggers <code>Login</code> action and it redirects me to my Azure AD SSO page and after login, it redirects me back to localhost. However, the request to the backend is still not authenticated.</p>
  
  <p><strong>Important</strong>:
  When I remove redirectUrl from login action, I'm redirected to the backend root instead of original origin (localhost). Any request from that origin (backend) is authenticated.</p>