I have used OAuth cookie authentication in the ASP.NET Core API project. All the APIs are authorized in this project. After successful login, all APIs can be accessible from a browser URL bar. When I try to access APIs in AJAX request from other domains always this will return Unauthorized
.
Here how to identify the user is authenticated or not from AJAX request?
API domain = ".apidomain.com"
Client domain = ".clientdomain.com"
API configuration:
services.AddAuthentication("oAuthSecurityScheme")
.AddOAuth("login.microsoftonline.com",
options =>
{
....
....
}).AddCookie(
"oAuthSecurityScheme",
options =>
{
options.LogoutPath = new PathString("/logout");
options.LoginPath = new PathString("/api/v1/account/authorize");
options.ExpireTimeSpan = new TimeSpan(7, 0, 0, 0);
options.SlidingExpiration = true;
options.Cookie.Name = "CustomerOAuthCookie";
options.Events.OnRedirectToLogin = UnAuthorizedResponseAsync;
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.HttpOnly = false;
});
Client Application:
$.ajax({
url: "https://localhost:44332/api/gettickets/1",
type: 'GET',
success: function (result)
{
alert(result);
console.log(result);
}
});
Note: When I access the below API in the browser directly it will return the proper response https://localhost:44332/api/gettickets/1