Retrieving session data from a different tab and website

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.

Answer №1

Through troubleshooting, it was discovered that the SameSite=Lax attribute was causing the cookie to not be read properly. To address this issue, modifications were made in the ASP.NET project to update the cookie with the SameSite=None parameter.

public class SameSiteMiddleware
{
    private readonly RequestDelegate _next;

    public SameSiteMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        // Code logic for updating cookies with required attributes
    }
}

In order to implement this functionality, the following code snippet should be added to the Configure method after calling app.UseAuthentication():

         app.UseMiddleware<SameSiteMiddleware>();

A valuable resource that assisted in resolving this issue can be found at:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`How can I customize the appearance of individual selected <v-list-item> across various sub-groups?`

As a newcomer to Vuetify and Vue in general, I am struggling to solve a specific issue. I need to create multiple sub-groups where only one option can be selected within each "parent" list. Consider an array of cats: options:["Crookshanks", "Garfield", " ...

When the browser back button is clicked, conceal the current div and reveal the previously hidden div

I'm faced with a situation where my website consists of multiple pages which I've achieved by displaying and hiding divs within a single html file. The issue I'm encountering is that the browser's back and forward buttons aren't fu ...

ReactJS form submissions failing to detect empty input values

My goal is to use react to console.log the input value. Below is the code I've created: import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component{ constructor() { super(); this.proce ...

Implementing Pagination for JSON-list items in AngularJS

On my webpage, I have a large list of Json data that is organized with paging. The issue arises when selecting categories from the listbox as the data does not display properly. When "All" is selected, each page shows the correct pageSize(4). However ...

The Node.js controller is in disarray

As a newcomer to javascript, node.js, and backend development in general, I am tackling the task of creating a controller for handling login page requests. My confusion lies in extracting data from a MYSQL table, user authentication, and working with the J ...

AngularJS - Increase the input date by 6 hours before converting it to JSON

Is there a way to add 6 hours to an input date in AngularJS? I attempted the following code: var eventStart = new Date ($scope.event.startdateid); var startDate = new Date ( eventStart ); startDate.setHours ( eventStart.getHours() + 6 ); event.startdate ...

Why is the location search not staying centered after resizing the map on Google Maps?

I am currently working on integrating Angular with Google Maps. I need to add some markers along with location search functionality. Additionally, I am including location information in a form. When the addMarker button is clicked, a form opens and the map ...

Extract the href value from an element and append it to the src attribute of an image

How can I extract the href link from the .image1 div class? <div class="image1"> <a href="/images/productA.jpg"> </a> </div> Then, how do I insert it into the image src shown below? <ul class="example"> <li class ...

What is the most secure method for conditionally wrapping input with state?

I used to check for errors and wrap the input and error message in a div conditionally. However, I faced an issue where the input would lose focus when re-rendered. Is there a way to wrap the input conditionally without losing focus on re-render if the err ...

How can you set a predetermined value for a dropdown menu after populating it with data from a Django database?

I currently have a query in my Views.py file that is used to populate a dropdown menu. The query works properly, but I need it to display a specific value that is stored in a variable based on the user's selection. For example, let's suppose we ...

Error in AngularJS when passing object to modal dialog

I'm facing a challenge with an AngularJS application I'm developing. It involves displaying a list of contacts, each accompanied by a button that triggers a modal containing a form for editing the contact information. The issue arises when attemp ...

Select the Best jQuery Package

Having a variety of packages available for selection. <div class="image-grid-item" data-search="select"> <input name="pack1" type="checkbox" style="display: none;"> </div> <div class="image-grid-item" data-search="select"> <inp ...

If there is a lack of text at the beginning, then insert the

I am currently trying to figure out a solution to automatically add our domain name if it is not included when entering the username. In the code snippet below for my form, I want the script to check if "domainname\" is present before the username. I ...

Not all dynamic content is loaded through Ajax requests on a single domain

I currently have my domain forwarded (cloaked) to The main page (index.html) utilizes Ajax for loading content. All content loads properly at the original host (moppy.co.uk/wtcdi). However, on the forwarded domain (whatthecatdragged.in), some content fai ...

What sort of JavaScript WYSIWYG text editor provides formula support?

Looking for a Javascript rich text editor that offers formula selection in the toolbar. Any recommendations? ...

Loading articles seamlessly in Yii using Ajax

I am currently working on a project where I need to display articles from databases, but every time an article is viewed, the whole page reloads. I would like to load articles without having to reload the page, and I believe this can be achieved using Ajax ...

Connecting Lavarel Pusher Socket in NUXT with SSR Mode

Looking to establish a connection between the Laravel Pusher Socket and NUTX.js (SSR Mode) Application. The code snippet above adds the socketio.js plugin file, but it seems to be causing some issues. Can anyone point out what might be going wrong? And ...

Need help implementing the disableGutters property on MTableToolbar?

I am currently using react material-table and I would like to customize the default toolbar styles by passing the prop disableGutters={true}, similar to how it's done in material-ui toolbar. Below is the code snippet that I have tried: <MaterialTab ...

Ensure the Image URL is valid before modifying the State in React/Next

This code snippet is written in React/Next.js with styled-components. Hey there, I have a component that displays a blog banner using a background-image. The URL for the image comes from a state variable that currently holds a default image path. const [b ...

Tips for animating input width as the size value changes during an ajax query transformation

This is my JavaScript code: function updatePriceDisplay() { $.ajax({ url:"query.php?currency=<?=$currencycode;?>" }).done(function(data) { $("value").attr("value", data).attr("size", data.length - 2); }); } updatePriceDi ...