Julia
Julia

Reputation: 25

CORS error for http 401 response status in .NET 7 API

I want to implement automatic token refreshing on status 401 in my React application using axios interceptors, but when I send request to backend API (.NET 7.0), with expired token, I receive cors error and no "response" object in axios error, passed to interceptor: request error

enter image description here

Access to XMLHttpRequest at 'https://localhost:44379/carts/0fe72f8a-9447-4c76-9ada-af831a5f618a' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I know that it is backend issue and most popular answer for it is to change middleware registration order, but mine should be fine:


builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", cors =>
        cors.WithOrigins("http://localhost:3000/", "http://localhost:3000")
        .AllowCredentials()
        .AllowAnyHeader()
        .AllowAnyMethod());
});

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseAccessTokenValidator();
app.MapControllers();
app.Run();

and my authentication middleware:

using System.Net;
using Microsoft.AspNetCore.Http;

namespace CleanTunedApp.Common.Authentication
{
    public class AccessTokenValidatorMiddleware : IMiddleware
    {
        private readonly IAccessTokenService _accessTokenService;

        public AccessTokenValidatorMiddleware(IAccessTokenService accessTokenService)
        {
            _accessTokenService = accessTokenService;
        }

        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            if (await _accessTokenService.IsCurrentActiveToken())
            {
                await next(context);

                return;
            }
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        }
    }
}

Any ideas how to fix CORS setup in dotnet app?

Upvotes: 0

Views: 105

Answers (1)

Julia
Julia

Reputation: 25

I wasn't able to fix CORS issue on backend side, so I created a workaround on frontend side:

  apiClient.interceptors.request.use(
    async (config) => {
      if (auth.isAuth && tokenExpiration <= new Date().getTime()) {
        await refreshAccessToken(auth.refreshToken, auth.token);
      }

      config.headers = {
        "Access-Control-Allow-Headers": "*",
        Authorization: `Bearer ${auth.token}`,
      };
      return config;
    },
    (error) => {
      Promise.reject(error);
    }
  );

Instead of using response interceptor with checking status of the response, I used request based one with tracking token expiration time.

Upvotes: 0

Related Questions