New Jan 6, 2025

Getting 401 error while sending the request

Libraries, Frameworks, etc. All from Newest questions tagged reactjs - Stack Overflow View Getting 401 error while sending the request on stackoverflow.com

I'm developing an application using ASP.NET + React. I have class User that can be of 3 roles. Logging in goes smoothly but after it I get 401 error when trying to send request to https://localhost:7260/api/User/Roles and don't see why.

Code of endpoint:

[HttpGet("Roles")] 
[Authorize] 
public async Task<IActionResult> GetUserRoles() 
{
    var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

if (userIdClaim == null || !int.TryParse(userIdClaim, out var userId)) { return Unauthorized(new { Message = "Invalid user token." }); }

var roles = await _userService.GetUserRolesAsync(userId);

if (roles == null) { return NotFound(new { Message = "User not found." }); }

return Ok(new { Roles = roles }); }

Code of App.jsx (only pieces that are connected to auth):

const [isAuthModalOpen, setAuthModalOpen] = useState(false);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [userRoles, setUserRoles] = useState([]);

// Load authentication state from localStorage on component mount useEffect(() => { const token = localStorage.getItem("jwtToken"); console.log("Token retrieved from localStorage:", token); // Debugging output if (token) { validateToken(token); } }, []);

const validateToken = async (token) => { console.log("Token during validation:", token); // Debugging output try { const response = await axios.get("https://localhost:7260/api/User/Roles", { headers: { Authorization: Bearer ${token} }, }); setIsLoggedIn(true); setUserRoles(response.data.Roles || []); // Use roles returned by the API } catch (error) { console.error("Failed to validate token:", error); handleLogout(); // Logout if the token is invalid } };

const handleLoginClick = () => { setAuthModalOpen(true); };

const handleAuthSuccess = (jwtToken) => { console.log("Token on successful login:", jwtToken); // Debugging output setIsLoggedIn(true); localStorage.setItem("jwtToken", jwtToken); // Store JWT token in localStorage setAuthModalOpen(false); validateToken(jwtToken); };

const handleLogout = () => { setIsLoggedIn(false); localStorage.removeItem("jwtToken"); setUserRoles([]); };

Not sure if it can be related to wrong Program.cs configuraton of jwt, but here it's:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["JwtSettings:Issuer"],
            ValidAudiences = new[] { builder.Configuration["JwtSettings:Audience"] },
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["JwtSettings:Secret"])
            )
        };
    });
Scroll to top