javascriptc#axiosember.jscors

CORS Ember.js C#/.net SessionId Header


I have an Ember.js SPA that's calling a .net service via AXIOS. Everything was working until I started checking the SessionId header to return a 401 when it's expired.

As long as the token is valid, my middle ware picks up the session ID and the call continues and everything is fine.

The problem is this, when the session id has expired, my C#/.net middle ware returns a 401. But AXIOS doesn't fill in the error.response.status: response is undefined.

What I want is for my AXIOS interceptor to have an error.response.status set to 401 so I can redirect the user to the sign-in route. My understanding of CORS, OPTIONS, and preflight requests is very weak. I've found lots of literature on various sites but it seems like the issues addressed there are simply receiving the request. So far, I've not found how to receive the response through AXIOS.

    // Add a response interceptor
    this._axios.interceptors.response.use(
        (response) => {
            return response
        },
        (error) => {
            if (error?.response?.status == 401) { // error is defined, but error.response is undefined.

On the C#/.net side of things

services.AddCors(options =>
{
options.AddPolicy(name: CorsDefaultPolicy,
    policy =>
    {
        policy.WithOrigins("https://localhost:4200", "https://*.MyCompany.io")
            .SetIsOriginAllowedToAllowWildcardSubdomains()
            .SetPreflightMaxAge(TimeSpan.FromHours(1))
            .AllowCredentials()
            .AllowAnyHeader()
            .AllowAnyMethod();
    });
});

Solution

  • I was stupid. Maybe this will keep someone else from being stupid too.

    I tried to force a return value from middleware. The commented lines below were the source of the problem. Don't try to write to the response to get a specific error message text. Just don't.

            catch (SessionExpiredException e)
            {
                var outputModel = new SuccessOutputModel
                {
                    WasSuccessful = false,
                    Status = "Session is invalid. Please try to sign-in again.",
                };
                logger.Error(e.Message);
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                //context.Response.ContentType = "application/json";
                //await context.Response.WriteAsync(JsonConvert.SerializeObject(outputModel));
            }