C
C#2mo ago
ItzYahPizza

✅ 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
Pobiega2mo ago
how are you making the request from the frontend? show code.
ItzYahPizza
ItzYahPizzaOP2mo 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
Pobiega2mo ago
Why axios in todays day and age?
Sehra
Sehra2mo ago
and the exact same token works in postman?
Pobiega
Pobiega2mo ago
Surely fetch would work just fine?
ItzYahPizza
ItzYahPizzaOP2mo 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
Pobiega2mo ago
hm, can you inspect the request in the browser network tab? make sure the headers are there etc
ItzYahPizza
ItzYahPizzaOP2mo ago
No description
Pobiega
Pobiega2mo 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
ItzYahPizzaOP2mo ago
been looking at my code seems all okay to mee i tried fetch and same thing
ItzYahPizza
ItzYahPizzaOP2mo ago
No description
ItzYahPizza
ItzYahPizzaOP2mo 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
ItzYahPizzaOP2mo ago
No description
ItzYahPizza
ItzYahPizzaOP2mo ago
no yea still error
Sehra
Sehra2mo ago
it says type:cors so might be a preflight not working
ItzYahPizza
ItzYahPizzaOP2mo 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
Sehra2mo ago
cors should come before auth well, in the UseCors part AddCors doesn't matter
ItzYahPizza
ItzYahPizzaOP2mo ago
No description
ItzYahPizza
ItzYahPizzaOP2mo ago
yeah i mean i dont think theres anythijng else really but i just cant seem to see the problem
Sehra
Sehra2mo ago
different ports
ItzYahPizza
ItzYahPizzaOP2mo ago
what do you mean?
Sehra
Sehra2mo ago
5015 vs 5173
ItzYahPizza
ItzYahPizzaOP2mo ago
5173 is my frontend 5015 is my backend
Sehra
Sehra2mo ago
could start with an allow-all policy and see if that work, then add stuff back and see when it breaks
ItzYahPizza
ItzYahPizzaOP2mo ago
can do that should i just delete options then?
Sehra
Sehra2mo ago
.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials()
ItzYahPizza
ItzYahPizzaOP2mo ago
sadly still didnt work. this is frustrating
Sehra
Sehra2mo ago
check the network tab, it might provide more info
ItzYahPizza
ItzYahPizzaOP2mo ago
No description
ItzYahPizza
ItzYahPizzaOP2mo ago
i changed my frontend to 5174 so
Sehra
Sehra2mo ago
this everything?
ItzYahPizza
ItzYahPizzaOP2mo ago
yeap basically im signing in. getting my token passing that token into my backend to get my tenant information
Sehra
Sehra2mo ago
UseRouting?
ItzYahPizza
ItzYahPizzaOP2mo ago
but it seems to be harder t do let me add that nope still the same
Sehra
Sehra2mo ago
make sure the cors status is not cached, it doesn't seem to perform an options request
ItzYahPizza
ItzYahPizzaOP2mo ago
how can i achieve that?
Sehra
Sehra2mo ago
usually some options in the dev tools to not use cache
Sehra
Sehra2mo ago
chrome version
No description
ItzYahPizza
ItzYahPizzaOP2mo 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
Sehra2mo ago
sorry, i don't do frontend, just know the basics
ItzYahPizza
ItzYahPizzaOP2mo 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
Pobiega2mo ago
I'm fairly sure its a CORS error ie, no tutorial for api + jwt will fix it since thats not the issue
Sehra
Sehra2mo ago
and postman is not a browser, it doesn't care about cors policies
Pobiega
Pobiega2mo ago
exactly
ItzYahPizza
ItzYahPizzaOP2mo 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
Pobiega2mo ago
sure
Harbour
Harbour2mo 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 User2mo ago
Message Not Public
Sign In & Join Server To View
ItzYahPizza
ItzYahPizzaOP2mo ago
ive changed it to 5174 but same thing happened i still get unauthorized
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View

Did you find this page helpful?