C
C#β€’2mo ago
Yarden

βœ… I'm trying to allow CORS on C# in order to allow cookies on my frontend, but I fail.

Hey, I'm trying to create a functionality that works this way: I login-in in the frontend -> The backend receive the username that logged-in with controller http method -> I store the username inside a state and show it to the user on the top-left of the screen. Now, I added those lines to the Program.cs file:
//CORS:
app.Use((ctx, next) =>
{
ctx.Response.Headers["Access-Control-Allow-Origin"] = "http://localhost:5173";
ctx.Response.Headers["Access-Control-Allow-Credentials"] = "true";

return next();
});
//CORS:
app.Use((ctx, next) =>
{
ctx.Response.Headers["Access-Control-Allow-Origin"] = "http://localhost:5173";
ctx.Response.Headers["Access-Control-Allow-Credentials"] = "true";

return next();
});
I don't get CORS message, but the username doesn't pass to the frontend, it gets an empty string. I added the network status with picture and the flow of my idea. I really need help, I have a tiny deadline with this project and I need to finish this part, so thanks for whoever helpsπŸ™ And I'm a beginner , so please communicate with basic language so I can follow!
No description
No description
16 Replies
Pobiega
Pobiegaβ€’2mo ago
Does your /api/auth/login endpoint return a username? Can you show the payload page in the debug tools? @Yarden Also, manually overriding the CORS headers in a middleware is... uh.. interesting, but C# has built in support for CORS and I'd probably recommend you use that instead
Yarden
YardenOPβ€’2mo ago
As always doesn't get notifications.. sorry Yes it does kind of As I figured out in the React discord that I use proxy, so CORS doesn't apply
Yarden
YardenOPβ€’2mo ago
This is the login: (first pic) This is the getUser: (second pic)
No description
No description
Yarden
YardenOPβ€’2mo ago
Inside React I just don't manage to get the value of the username I'm using states but it doesn't store the value, and I'm trying to figure out the problem but I don't manage
Yarden
YardenOPβ€’2mo ago
//const res = await axios.post("/api/auth/login", loginAttempt);
const res = await axios.post("/api/auth/login", loginAttempt, { headers: { "Content-Type": "application/json" } });


if(res?.status === 200 || res?.status === 201){

axios.get("/api/auth/getUsername")
.then(response => setUserNameLabel(response.data));

console.log("usernameLabel is: " + usernameLabel);
//const res = await axios.post("/api/auth/login", loginAttempt);
const res = await axios.post("/api/auth/login", loginAttempt, { headers: { "Content-Type": "application/json" } });


if(res?.status === 200 || res?.status === 201){

axios.get("/api/auth/getUsername")
.then(response => setUserNameLabel(response.data));

console.log("usernameLabel is: " + usernameLabel);
No description
Yarden
YardenOPβ€’2mo ago
It seems like I can't store the value from the http get call Hopefully I gave the info you asked for. And I looked at discord 1 hour after the creation of the post and saw no answer, something it totally broken with my discord
Pobiega
Pobiegaβ€’2mo ago
Response.Data will not just be the string btw Its an object with a username prop
Yarden
YardenOPβ€’2mo ago
Yeah I know, I tried everything... I tried to get the value it self by data.username but once I update the state with it, it disappears I don't manage to find the problem
Yarden
YardenOPβ€’2mo ago
console.log("Username is:", usernameLabel);
if(res?.status === 200 || res?.status === 201){

const userRes = await axios.get("/api/auth/getUsername"); // cookie will be sent
setUserNameLabel(userRes.data.username);

console.log("Type of usernameLabel:", typeof userRes.data.username);
console.log("userRes.data.username:", userRes.data.username);

console.log("usernameLabel is: " + usernameLabel);


<UsernameHeader usernameLabel = {usernameLabel}/>
console.log("Username is:", usernameLabel);
if(res?.status === 200 || res?.status === 201){

const userRes = await axios.get("/api/auth/getUsername"); // cookie will be sent
setUserNameLabel(userRes.data.username);

console.log("Type of usernameLabel:", typeof userRes.data.username);
console.log("userRes.data.username:", userRes.data.username);

console.log("usernameLabel is: " + usernameLabel);


<UsernameHeader usernameLabel = {usernameLabel}/>
I manage to print the username which is : yaryaryar But once I update the state with setUsernameLabel and tried to print: usernameLabel it prints nothing. Pretty redicilous
No description
Pobiega
Pobiegaβ€’2mo ago
so your issue is with the react code then
qqdev
qqdevβ€’2mo ago
^ I think so too
Yarden
YardenOPβ€’2mo ago
Yep When I created this post I didn't know where the problem is, but now it seems like react. It seems like I managed to store the value inside the state, but now I have other problems as always. I will check it out Thank you a lot for the help I appriciate that
Pobiega
Pobiegaβ€’2mo ago
Without knowing react at all, I somehow managed to make this all work When I say I, I mean claude πŸ˜„
qqdev
qqdevβ€’2mo ago
Have a good one guys πŸ‘‹
Pobiega
Pobiegaβ€’2mo ago
Absolutely not sure this is the way to go, but it created an AuthProvider that wrapped the Outlet component(?), created an authcontext that handles the login/logout and updating of the user state, two components: loginform and logout button...
import React from 'react';
import { useAuth } from '../contexts/AuthContext';

export const LogoutButton: React.FC = () => {
const { logout, user } = useAuth();

const handleLogout = () => {
logout();
};

return (
<div className="max-w-[300px] w-full space-y-6 px-4">
<nav className="rounded-3xl border border-gray-200 p-6 dark:border-gray-700 space-y-4">
<p className="leading-6 text-gray-700 dark:text-gray-200 text-center">
Welcome, {user?.username || 'User'}!
</p>
<button
onClick={handleLogout}
className="w-full bg-red-600 text-white p-2 rounded hover:bg-red-700"
>
Logout
</button>
</nav>
</div>
);
};
import React from 'react';
import { useAuth } from '../contexts/AuthContext';

export const LogoutButton: React.FC = () => {
const { logout, user } = useAuth();

const handleLogout = () => {
logout();
};

return (
<div className="max-w-[300px] w-full space-y-6 px-4">
<nav className="rounded-3xl border border-gray-200 p-6 dark:border-gray-700 space-y-4">
<p className="leading-6 text-gray-700 dark:text-gray-200 text-center">
Welcome, {user?.username || 'User'}!
</p>
<button
onClick={handleLogout}
className="w-full bg-red-600 text-white p-2 rounded hover:bg-red-700"
>
Logout
</button>
</nav>
</div>
);
};
accessing the user seems very straight forward at least πŸ˜„

Did you find this page helpful?