The task at hand involves managing a PHP website (mysite.com) and an ASP.NET website (shop.mysite.com). The client's request is to implement a single sign-on solution for both sites. My approach is to develop a function on the ASP.NET site that can provide the necessary information to the PHP site.
This function in ASP.NET is named "IsUserLoggedIn" and it returns a JSON object containing the username and an array of roles.
Below is a summarized version of the function:
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> IsUserLoggedIn()
{
try
{
if (HttpContext.Request.Headers["api-key"][0] != configuration["ApiKey"])
{
HttpContext.Response.StatusCode = 200;
return Json(new { authenticated = "no key", roleId = "" });
}
if (HttpContext.User.Identity.IsAuthenticated)
{
var user = await userOperations.GetUser.Execute(HttpContext.User);
var companyUser = await companyRepository.GetUser(user.Id, user.ActiveCompanyId);
var roles = new List<String>();
if (companyUser.Company.CustomerRoles != null)
{
roles.AddRange(companyUser.Company.CustomerRoles);
}
if (companyUser.UserCompanies != null)
{
foreach (var company in companyUser.UserCompanies)
{
if (company.CustomerRoles != null)
{
roles.AddRange(company.CustomerRoles);
}
}
}
HttpContext.Response.StatusCode = 200;
return Json(new { authenticated = "yes", User = user, roleId = roles });
}
else
{
HttpContext.Response.StatusCode = 200;
return Json(new { authenticated = "not auth", roleId = "" });
}
}
catch (AuthenticationException e)
{
HttpContext.Response.StatusCode = 200;
return Json(new { authenticated = "error", roleId = "", e });
}
}
Testing this function by accessing shop.mysite.com/User/IsUserLoggedIn with the appropriate api-key in the header results in the expected JSON object:
{
"authenticated": "yes",
"user": {
"id": 17085,
"username": "cdavis",
"verified": true,
"activeCompanyId": "TEST001"
},
"roleId": [
"NGFE"
]
}
However, attempting to retrieve this data using JavaScript's fetch API returns a JSON object indicating that no authorized user is logged in. Below is the JavaScript code I used on mysite.com:
async function checkUserLoggedIn() {
try {
const response = await fetch('https://' + custom_script_vars.api_url + '/User/IsUserLoggedIn', {
method: 'GET',
headers: {
'api-key': custom_script_vars.api_key,
},
credentials: 'include',
});
console.log('Response status:', response.status);
if (response.ok) {
const jsonData = await response.json();
console.log('User logged in:', jsonData);
const phpEndpoint = custom_script_vars.theme_directory + '/set-session.php';
// Use AJAX or another fetch to pass the JSON data to your PHP method
await fetch(phpEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ companyResourcesSessionUserLoggedIn: jsonData }),
});
console.log('User logged in:', jsonData);
} else {
console.error('Failed to check user login status:', response.status);
}
} catch (error) {
console.error('Error during user login check:', error);
}
}
The JSON object received from the JavaScript fetch operation is as follows:
{
"authenticated": "not auth",
"roleId": ""
}
Is what I'm trying to achieve not feasible? I have tested this in both Chrome and Edge browsers with consistent outcomes. If you have encountered similar challenges, I would appreciate any alternative solutions you could suggest.