How to make ASP.NET Core JWT Bearer Authentication check the Authorization header first before checking the Cookies?

To give you some context:

I am trying to implement a Refresh/Access Token Authentication security to a simple Web API using ASPNET Core. Its going well so far.. It does work! Just not as expected.

To my understanding with this kind of setup the first thing that the app is supposed to check would be the JwtBearer within the Authentication. In this case the access token that will be send within the Header.

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = builder.Configuration["JWT:Issuer"], // Ensure this matches your token's Issuer
        ValidateAudience = false, // Assuming you're not validating audience, change if necessary
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(builder.Configuration["JWT:Key"]!)),
        ValidateLifetime = true, // Ensure lifetime validation is enabled
        ClockSkew = TimeSpan.Zero // Optional: set this to zero to remove any time drift
    };

    options.Events = new JwtBearerEvents
    {
        OnMessageReceived = context =>
        {
            // Check if the "auth_token" cookie is present and extract the token
            if (context.Request.Cookies.ContainsKey("auth_token"))
            {
                context.Token = context.Request.Cookies["auth_token"];
            }
            return Task.CompletedTask;
        }
    };
});
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminPolicy", policy => policy.RequireRole("Admin"));
    options.AddPolicy("UserPolicy", policy => policy.RequireRole("User"));
});

Now the logic behind how the security within this app would work like is:

Every Request will be check for the header(Access Token) Which will have a short lifespan. Every few mins within the Client side (React) There will be a useEffect that will try to ReFetch said access token with the use of the next Endpoint:

 [HttpGet]
        public async Task<IActionResult> RefreshAccessToken()
        {
            // Access HttpContext from the ControllerBase class (no need to pass it as a parameter)
            if (!HttpContext.Request.Cookies.ContainsKey("auth_token"))
                return StatusCode(401, "Unauthorized");

            var token = HttpContext.Request.Cookies["auth_token"];

            // Decode the JWT to extract claims
            var decodedClaims = _refreshTokenServices.DecodeJWT(token!);

            if (decodedClaims == null)
                return StatusCode(401, "Unauthorized");

            // Retrieve the username claim from the decoded JWT
            var usernameClaim = decodedClaims?.FindFirst(JwtRegisteredClaimNames.Sub);

            // Check if the username claim exists
            if (usernameClaim == null)
                return StatusCode(401, "Unauthorized");

            var username = usernameClaim.Value;  // Use the 'Value' to get the actual username

            // Find the user by username
            var foundUser = await _userManager.FindByNameAsync(username);

            // If user is not found, return unauthorized
            if (foundUser == null)
                return StatusCode(401, "Unauthorized");

            // Create a new access token for the user
            var accessToken = _accessTokenServices.CreateToken(foundUser);

            // Return the new access token
            return Ok(new { AccessToken = accessToken.Result });
        }

Now I will also fill each API fetch call with a refreshAccessToken that will be called when the StatusCode would be 401. And it will just do nothing and return the Error if its 403. Meaning in case the Refetch fails or something all Api Calls from the frontend would be secure.

Now I have this side of the logic figured out. But thing is for some reason. This structure completely ignores the Bearer Token.

Doing some testing I noticed It only checks for the HttpOnly meaning the Refresh Token.

Since said Refresh token only has Username and Id Info.
It is useless for the Role Based Access Control side of the Application. What I find weird is that if I completely delete the Refresh token meaning there is not a single HttpOnly Cookie only then will it bother to check for the Bearer Token.. Now I know this is probably due to a misuse or misconfiguration on my part but I legit have no idea how to proceed.

I am trying to use Attributes in order to handle my Protected routes like so:

 [HttpGet]
        [Route("admin-test")]
        [Authorize(Roles = "Admin")]
        public IActionResult Admin()
        {
            return Ok("Admin");
        }

I have seen some guides and they say to do something like Request.Header and just straight up check the Header for the correct Token. But I really want to implement this functionality using Attributes as I believe they are cleaner looking but if the only way to implement Refresh/Access Authentication/Authorization is without it so be it.

Any guidance or advice into how to implement this functionality would be highly appreciated!

EDIT: In case necessary this is how I am sending back the Cookies:

 [HttpPost]
        [Route("login")]
        public async Task<IActionResult> Login([FromBody] LoginRequestDto loginModel)
        {
            if (!ModelState.IsValid) return BadRequest("Invalid Input Data");
            var user = await _userManager.Users.FirstOrDefaultAsync(u => u.UserName == loginModel.Username);
            if (user == null) return BadRequest("Wrong Username or Password");
            var passwordMatch = await _userManager.CheckPasswordAsync(user, loginModel.Password);
            if (!passwordMatch) return BadRequest("Wrong Username or Password");
            var refreshToken = _refreshToken.CreateToken(user);
            Response.Cookies.Append("auth_token", refreshToken, new CookieOptions()
            {
                HttpOnly = true,
                SameSite = SameSiteMode.None,
                Secure = false,  //For dev purposes
                Expires = DateTime.Now.AddDays(7)
            });
            var accessToken = _accessToken.CreateToken(user);
            return Ok(new { AcessToken = accessToken.Result });
        }
    }

And this is how the Tokens are being created:

   public async Task<string> CreateToken(Usuario usuario)
        {
            var userRoles = await _userManager.GetRolesAsync(usuario);
            var authClaims = new List<Claim>()
    {
        new Claim(JwtRegisteredClaimNames.Sub, usuario.UserName!),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
    };
            authClaims.AddRange(userRoles.Select(role => new Claim(ClaimTypes.Role, role)));

            // Ensure the expiration time is UTC to avoid any timezone issues
            var expiresAt = DateTime.UtcNow.AddMinutes(15);

            var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(authClaims),
                Expires = expiresAt, // Set expiration time
                IssuedAt = DateTime.UtcNow, // Set the issue time
                NotBefore = DateTime.UtcNow.AddSeconds(5), // Set the 'NotBefore' to a few seconds after issue time
                SigningCredentials = creds,
                Issuer = _config["JWT:Issuer"]
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }

Only difference between the Access Token and the Refresh token is the duration and the Claims. Access Holds the userRoles whereas the Refresh Token only holds information about the user itself like the Username and its Id.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật