问题
I have Asp.Net core backend running in Azure. HTML/JS frontend running on localhost, using CORS to communicate with backend
When both, frontend and backend are in localhost, or they are both in Azure, the authentication works -> Azure AD app is setup correctly.
Here is how I log in:
[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);
}
}
so from localhost, I then redirect to:
https://myapp.azurewebsites.net/Account/Login?returnUrl=localhost:12345
which triggers Login
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.
Important: 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.
回答1:
I had to explicitelly tell javascript to include authentication headers:
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
for more details: https://docs.microsoft.com/en-us/aspnet/core/security/cors#credentials-in-cross-origin-requests
EDIT: in case of chrome and opera, which implements SameSite attribute of cookies, you also have to setup authentication cookie like this:
services.AddAuthentication(...)
.AddCookie(option => option.Cookie.SameSite = SameSiteMode.None)
.AddOpenIdConnect(...)
来源:https://stackoverflow.com/questions/46485755/authenticate-cors-request-using-openidconnect-and-azure-ad