使用OpenIdConnect和Azure AD验证CORS请求

问题描述 投票:0回答:1

我在Azure中运行Asp.Net核心后端。在localhost上运行的HTML / JS前端,使用CORS与后端进行通信

如果前端和后端都在localhost中,或者它们都在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);
    }
}

所以从localhost,我然后重定向到:

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

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

重要提示:当我从登录操作中删除redirectUrl时,我被重定向到后端根而不是原始源(localhost)。来自该来源(后端)的任何请求都经过身份验证。

c# asp.net-core cors azure-active-directory openid-connect
1个回答
0
投票

我必须明确告诉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,它实现了Cookie的SameSite属性,你还必须像这样设置身份验证cookie:

 services.AddAuthentication(...)
         .AddCookie(option => option.Cookie.SameSite = SameSiteMode.None)
         .AddOpenIdConnect(...)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.