✅ JWT AUTH HELP. Postman Get Request Works. But when using the api in the frontend it doesnt

Hi, can anyone here help me? when i use JWT authentication in postman it works but when i use it on my react frontend it doesnt work and just returns unauthorized. been stuck with this error for 3 days and i really need help figuring this out.
50 Replies
Pobiega
Pobiega2w ago
how are you making the request from the frontend? show code.
ItzYahPizza
ItzYahPizzaOP2w ago
import axios from "axios";

export const getTenants = async () => {
try {
const token = localStorage.getItem("token");

console.log("Token being used for request:", token);

if (!token) {
console.error("No authentication token found");
alert("You must log in first!");
return null;
}

const headers = {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
};

console.log("🛠 Request Headers:", headers);

const response = await axios.get("http://localhost:5015/api/tenant", { headers });

console.log("Tenant Data:", response.data);
return response.data;
} catch (error: any) {
console.error("Error fetching tenants:", error.response);
if (error.response) {
console.error("Response Data:", error.response.data);
console.error("Status Code:", error.response.status);
console.error("Headers:", error.response.headers);
}
alert("Failed to fetch tenants. Please try again.");
return null;
}
};
import axios from "axios";

export const getTenants = async () => {
try {
const token = localStorage.getItem("token");

console.log("Token being used for request:", token);

if (!token) {
console.error("No authentication token found");
alert("You must log in first!");
return null;
}

const headers = {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
};

console.log("🛠 Request Headers:", headers);

const response = await axios.get("http://localhost:5015/api/tenant", { headers });

console.log("Tenant Data:", response.data);
return response.data;
} catch (error: any) {
console.error("Error fetching tenants:", error.response);
if (error.response) {
console.error("Response Data:", error.response.data);
console.error("Status Code:", error.response.status);
console.error("Headers:", error.response.headers);
}
alert("Failed to fetch tenants. Please try again.");
return null;
}
};
then i use useeffect to run it
Pobiega
Pobiega2w ago
Why axios in todays day and age?
Sehra
Sehra2w ago
and the exact same token works in postman?
Pobiega
Pobiega2w ago
Surely fetch would work just fine?
ItzYahPizza
ItzYahPizzaOP2w ago
import { Button } from "@/components/ui/button";
import { getTenants } from "../api/tenant";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

interface Tenant {
tenantId: string;
name: string;
}

export default function TenantSites() {
const [tenants, setTenants] = useState<Tenant[]>([]);

const navigate = useNavigate();

useEffect(() => {
const fetchTenants = async () => {
const data = await getTenants();
if (data) {
setTenants(data); // Set tenant data in state
}
};

fetchTenants();
}, []);

return (
<div>
<h1>Tenant Sites</h1>
{tenants.length > 0 ? (
<ul>
{tenants.map((tenant) => (
<li key={tenant.tenantId}>
<strong>{tenant.name}</strong> ({tenant.tenantId})
</li>
))}
</ul>
) : (
<p>No tenants found.</p>
)}
</div>
);
}
import { Button } from "@/components/ui/button";
import { getTenants } from "../api/tenant";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

interface Tenant {
tenantId: string;
name: string;
}

export default function TenantSites() {
const [tenants, setTenants] = useState<Tenant[]>([]);

const navigate = useNavigate();

useEffect(() => {
const fetchTenants = async () => {
const data = await getTenants();
if (data) {
setTenants(data); // Set tenant data in state
}
};

fetchTenants();
}, []);

return (
<div>
<h1>Tenant Sites</h1>
{tenants.length > 0 ? (
<ul>
{tenants.map((tenant) => (
<li key={tenant.tenantId}>
<strong>{tenant.name}</strong> ({tenant.tenantId})
</li>
))}
</ul>
) : (
<p>No tenants found.</p>
)}
</div>
);
}
yes exact same token i get from logging in works in postman i could try it with fetch
Pobiega
Pobiega2w ago
hm, can you inspect the request in the browser network tab? make sure the headers are there etc
ItzYahPizza
ItzYahPizzaOP2w ago
No description
Pobiega
Pobiega2w ago
okay good Well, somehow the requests are not identical, thats all I can tell you for sure if it works in postman, your backend works. It might be a whitespace somewhere or something
ItzYahPizza
ItzYahPizzaOP2w ago
been looking at my code seems all okay to mee i tried fetch and same thing
ItzYahPizza
ItzYahPizzaOP2w ago
No description
ItzYahPizza
ItzYahPizzaOP2w ago
export const getTenants = async () => {
const response = await fetch("http://localhost:5015/api/tenant", {
headers: {
"Authorization": `Bearer ${localStorage.getItem("token")}`
}
});

if (!response.ok) {
console.error("Failed to fetch tenants:", response);
alert("Failed to fetch tenants. Please try again.");
return null;
}
}
export const getTenants = async () => {
const response = await fetch("http://localhost:5015/api/tenant", {
headers: {
"Authorization": `Bearer ${localStorage.getItem("token")}`
}
});

if (!response.ok) {
console.error("Failed to fetch tenants:", response);
alert("Failed to fetch tenants. Please try again.");
return null;
}
}
oh wait no hold on
ItzYahPizza
ItzYahPizzaOP2w ago
No description
ItzYahPizza
ItzYahPizzaOP2w ago
no yea still error
Sehra
Sehra2w ago
it says type:cors so might be a preflight not working
ItzYahPizza
ItzYahPizzaOP2w ago
builder.Services.AddAuthorization();
builder.Services.AddControllers();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowFrontend",
policy => policy.WithOrigins("http://localhost:5173")
.AllowAnyHeader()
.WithExposedHeaders("Authorization")
.AllowAnyMethod()
.AllowCredentials());
});
builder.Services.AddAuthorization();
builder.Services.AddControllers();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowFrontend",
policy => policy.WithOrigins("http://localhost:5173")
.AllowAnyHeader()
.WithExposedHeaders("Authorization")
.AllowAnyMethod()
.AllowCredentials());
});
Sehra
Sehra2w ago
cors should come before auth well, in the UseCors part AddCors doesn't matter
ItzYahPizza
ItzYahPizzaOP2w ago
No description
ItzYahPizza
ItzYahPizzaOP2w ago
yeah i mean i dont think theres anythijng else really but i just cant seem to see the problem
Sehra
Sehra2w ago
different ports
ItzYahPizza
ItzYahPizzaOP2w ago
what do you mean?
Sehra
Sehra2w ago
5015 vs 5173
ItzYahPizza
ItzYahPizzaOP2w ago
5173 is my frontend 5015 is my backend
Sehra
Sehra2w ago
could start with an allow-all policy and see if that work, then add stuff back and see when it breaks
ItzYahPizza
ItzYahPizzaOP2w ago
can do that should i just delete options then?
Sehra
Sehra2w ago
.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials()
ItzYahPizza
ItzYahPizzaOP2w ago
sadly still didnt work. this is frustrating
Sehra
Sehra2w ago
check the network tab, it might provide more info
ItzYahPizza
ItzYahPizzaOP2w ago
No description
ItzYahPizza
ItzYahPizzaOP2w ago
i changed my frontend to 5174 so
Sehra
Sehra2w ago
this everything?
ItzYahPizza
ItzYahPizzaOP2w ago
yeap basically im signing in. getting my token passing that token into my backend to get my tenant information
Sehra
Sehra2w ago
UseRouting?
ItzYahPizza
ItzYahPizzaOP2w ago
but it seems to be harder t do let me add that nope still the same
Sehra
Sehra2w ago
make sure the cors status is not cached, it doesn't seem to perform an options request
ItzYahPizza
ItzYahPizzaOP2w ago
how can i achieve that?
Sehra
Sehra2w ago
usually some options in the dev tools to not use cache
Sehra
Sehra2w ago
chrome version
No description
ItzYahPizza
ItzYahPizzaOP2w ago
yeah. same things same errors but ill maybe jsut go ahead and sleep this off. might just redo the whole thing again tomorrow and see where that leads me. do you know a good web api + JWT authentication video that is easy to understand?
Sehra
Sehra2w ago
sorry, i don't do frontend, just know the basics
ItzYahPizza
ItzYahPizzaOP2w ago
no problem bro! thanks for helping me @Sehra @Pobiega i will succeed this tomorrow. or be super burnt out from it. but thanks guys
Pobiega
Pobiega2w ago
I'm fairly sure its a CORS error ie, no tutorial for api + jwt will fix it since thats not the issue
Sehra
Sehra2w ago
and postman is not a browser, it doesn't care about cors policies
Pobiega
Pobiega2w ago
exactly
ItzYahPizza
ItzYahPizzaOP2w ago
okay ill see how i can check for CORS error tomorrow but for now i need to rest cause ive been at it for a couple of hours
Pobiega
Pobiega2w ago
sure
Harbour
Harbour2w ago
Is your port correct It says 5173 on your c# app but the request here says 5174 on origin 5173 here
Unknown User
Unknown User2w ago
Message Not Public
Sign In & Join Server To View
ItzYahPizza
ItzYahPizzaOP2w ago
ive changed it to 5174 but same thing happened i still get unauthorized
Unknown User
Unknown User2w ago
Message Not Public
Sign In & Join Server To View

Did you find this page helpful?