使用OpenIdConnect和Azure AD验证CORS请求

问题描述:

我有在Azure中运行的Asp.Net核心后端。 在本地主机上运行的HTML/JS前端,使用CORS与后端进行通信使用OpenIdConnect和Azure AD验证CORS请求

当前端和后端都位于本地主机中,或者它们都在Azure中时,身份验证正常工作 - > Azure AD应用程序安装正确。

这是我如何登录:

[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); 
    } 
} 

所以从本地主机的,我然后重定向到:

https://myapp.azurewebsites.net/Account/Login?returnUrl=localhost:12345 

触发Login行动并重定向我到我的Azure的AD SSO页和后登录,它将我重定向回localhost。但是,对后端的请求仍未通过身份验证。

重要: 当我登录操作删除的redirectUrl,我重定向到后端的根,而不是原来的原点(本地主机)。来自该源(后端)的任何请求都经过身份验证。

+0

Hi @Liero,请你分享一下mor电子信息?这将有助于查看这些请求的所有响应标头。 (原来的和重定向) –

+0

好吧,用'xhr.withCredentials = true;'我已经设法在Edge中工作,看我的恶意软件。但是,它仍然无法在Chrome中使用。边缘发送2个Cookie:'ARRAfinity = ... AspNetCore.Cookies = ...'。 Chrome只发送ARRAfinity,我不知道为什么 – Liero

我不得不explicitelly告诉JavaScript来包括认证报头:

var xhr = new XMLHttpRequest(); 
xhr.withCredentials = true; 

了解更多详情:https://docs.microsoft.com/en-us/aspnet/core/security/cors#credentials-in-cross-origin-requests

编辑:在Chrome和Opera的情况下,实现了饼干SameSite属性,还必须设置像这样的身份验证cookie:

services.AddAuthentication(...) 
     .AddCookie(option => option.Cookie.SameSite = SameSiteMode.None) 
     .AddOpenIdConnect(...)