JWT in front-end

Hi, I'm trying to use JWT as a auth for my app (because I also plan to create a mobile app) So I've made two projects : Project.Api and Project.Web (which is basically just the front-end) but i don't know how to correctly setup jwt for the front end project
134 Replies
P A T R I C K
P A T R I C KOP3d ago
don't hesitate to ping or dm me or using cookie is just easier ? because idk if using cookies for a BFF structure is better
Anchy
Anchy3d ago
Where are you getting your JWT from? Are you using an identity provider or do you have your own auth api endpoint to consume it from? What scheme do you want to consume the JWT as in your API as well? If you have an external identity provider already that provides you with a JWT and you are using ASP.NET Core for the backend API then you could use the JWT Bearer scheme, this will allow you to pass the JWT through the Authorization header with the format Authorization: Bearer JWT_HERE You can also use HTTP only cookies but I believe when you are making requests from your frontend you will have to allow credentials in your request and you will need to parse the cookie yourself in the backend API Also don't forget to create a CORS policy and apply it, otherwise you will not be able to make requests
P A T R I C K
P A T R I C KOP3d ago
well i was thinking about using aspnet core identity (ef) and i use the JwtDefaults.AuthenticationScheme value okay thanks, im gonna check that tomorrow
Byron
Byron3d ago
I have been looking into similar things, and it seems like BFF + SessionCookie is easier if you don't have a full IDP (Okta, entra, Identiy Server, IAM, etc) (not an expert) I have less than 100k users, and all of my webapps + apis are on the same domain so I am going to shoot for a session cookie set to Lax for my auth
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
okay it is what i did first but the issue is that it seems like the cookie isn't sent back
[HttpPost("login")]
public async Task<ActionResult> Login(LoginRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

var user = await _userManager.FindByEmailAsync(request.Email);
if (user is null)
{
return Unauthorized(new RequestError
{
Code = HttpStatusCode.Unauthorized,
Message = ErrorMessages.UserNotFound
});
}

bool valid = await _userManager.CheckPasswordAsync(user, request.Password);
if (!valid)
{
return Unauthorized(new RequestError
{
Code = HttpStatusCode.Unauthorized,
Message = ErrorMessages.InvalidCredentials
});
}

var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Email, user.Email)
};

var identity = new ClaimsIdentity(claims, IdentityConstants.ApplicationScheme);
var principal = new ClaimsPrincipal(identity);

await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal);

return Ok();
}
[HttpPost("login")]
public async Task<ActionResult> Login(LoginRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

var user = await _userManager.FindByEmailAsync(request.Email);
if (user is null)
{
return Unauthorized(new RequestError
{
Code = HttpStatusCode.Unauthorized,
Message = ErrorMessages.UserNotFound
});
}

bool valid = await _userManager.CheckPasswordAsync(user, request.Password);
if (!valid)
{
return Unauthorized(new RequestError
{
Code = HttpStatusCode.Unauthorized,
Message = ErrorMessages.InvalidCredentials
});
}

var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Email, user.Email)
};

var identity = new ClaimsIdentity(claims, IdentityConstants.ApplicationScheme);
var principal = new ClaimsPrincipal(identity);

await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal);

return Ok();
}
this is my API login action and even tho credentials are valid and the Ok() is executed, the cookie isn't sent back to the browser
[HttpPost("login")]
public async Task<ActionResult> Login([FromForm] LoginRequest request)
{
if (!ModelState.IsValid)
{
return View(request);
}

var response = await _http.PostAsJsonAsync("https://localhost:9500/auth/login", request);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);

return View(request);
}

return RedirectToAction("Index", "Home");
}
[HttpPost("login")]
public async Task<ActionResult> Login([FromForm] LoginRequest request)
{
if (!ModelState.IsValid)
{
return View(request);
}

var response = await _http.PostAsJsonAsync("https://localhost:9500/auth/login", request);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);

return View(request);
}

return RedirectToAction("Index", "Home");
}
this is my front-side, nothing special
// other services blablabla
builder.Services.AddIdentity<User, IdentityRole>(options =>
{
var section = builder.Configuration.GetSection("PasswordComplexity");

options.Password.RequireNonAlphanumeric = section.GetValue<bool>("RequireNonAlphanumeric");
options.Password.RequireLowercase = section.GetValue<bool>("RequireLowercase");
options.Password.RequireUppercase = section.GetValue<bool>("RequireUppercase");
options.Password.RequireDigit = section.GetValue<bool>("RequireDigit");
options.Password.RequiredLength = section.GetValue<int>("RequiredLength");
})
.AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "Poppsza.Auth";
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.None;
options.Cookie.HttpOnly = true;
options.LoginPath = "/Auth/Login";
options.LogoutPath = "/Auth/Logout";
options.AccessDeniedPath = "/Auth/Denied";
});
// other services blablabla
builder.Services.AddIdentity<User, IdentityRole>(options =>
{
var section = builder.Configuration.GetSection("PasswordComplexity");

options.Password.RequireNonAlphanumeric = section.GetValue<bool>("RequireNonAlphanumeric");
options.Password.RequireLowercase = section.GetValue<bool>("RequireLowercase");
options.Password.RequireUppercase = section.GetValue<bool>("RequireUppercase");
options.Password.RequireDigit = section.GetValue<bool>("RequireDigit");
options.Password.RequiredLength = section.GetValue<int>("RequiredLength");
})
.AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "Poppsza.Auth";
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.None;
options.Cookie.HttpOnly = true;
options.LoginPath = "/Auth/Login";
options.LogoutPath = "/Auth/Logout";
options.AccessDeniedPath = "/Auth/Denied";
});
and this is my API's Program.cs file the thing is that i also wanna create a mobile app that will connect to this api i've tried jwt and jwt is kinda odd to me for the moment and i've used aspnet core identity cookies auth much longer but it was only on aspnetcore mvc apps
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
No description
P A T R I C K
P A T R I C KOP2d ago
it will look like that
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
no worries answer me when you will be able to
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
okay hold on
P A T R I C K
P A T R I C KOP2d ago
GitHub
GitHub - kubikpatrick/Poppsza
Contribute to kubikpatrick/Poppsza development by creating an account on GitHub.
P A T R I C K
P A T R I C KOP2d ago
thats it what i want is the API handling the auth, data, db, etc and clients (desktop, mobile or web) to consume it by being logged it, that's it. and the front will, not be hosted on the same domain, usually it's gonna be hosted on localhost
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
idk why it's duplicated but those are just .editorconfig files analyzers
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
vs did it
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
okay i didn't know that thanks well what didnt u understand ?
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
so my Web also must have a auth setup?
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
AuthZ is authorization authn is identity ?
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
i know the goals right authn is to validate what users say they are authz is to validate what users say they have access to right?
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
yes okay what i wanna do i’ll explain u what i wanna do
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
okay hold on what i wanna do is self hosted a geolocation tracker
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
people host their API server and the web client is supposed to connect to the API and then to log in
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
like API is where everything happens clients (mobile, web) just consume it
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
nw mb 5 mins lemme take a shower
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
yes ik
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
oh
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
i see just not practical
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
ohh okay i see so in my case jwt is the best option ?
Unknown User
Unknown User2d ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP2d ago
okay i see so basically ok just lemme explain so at least u can understand the API is hosted online and clients (mobile, web, etc) should enter the API’s uri THEN login with an account email/password but i just want to code the auth in the right way for every platform the api is autonomous (db, ws, auth) so u sayin that jwt the best way ? i see
Unknown User
Unknown User21h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP20h ago
oh yes my bad okay 5 misn basically "localhost" can be the .Web idk how to be clear it's actually really simple to understand but i cant explain it in the right way cause english ain't my first language like api should be autonomous
P A T R I C K
P A T R I C KOP20h ago
No description
P A T R I C K
P A T R I C KOP20h ago
clients may not be "hosted" they are supposed to work normally even in localhost as long as the API is accessible ykwim
Unknown User
Unknown User20h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP20h ago
yes i will require an account for EVERY client they are not supposed to be anonymous at all i've actually coded some shitty ass jwt auth
Unknown User
Unknown User20h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP20h ago
wdym
Unknown User
Unknown User20h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP20h ago
no an online provider? no like auth0?
Unknown User
Unknown User20h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP20h ago
i don't think so, i think it'll complicate the deployment for those who want to use the app
Unknown User
Unknown User20h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP20h ago
ahh okay i got it yeah i'm my own authority im signing it, validating it
P A T R I C K
P A T R I C KOP20h ago
No description
P A T R I C K
P A T R I C KOP20h ago
u're talking about this right ?
Unknown User
Unknown User20h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP20h ago
why
Unknown User
Unknown User20h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP20h ago
yeah i forgot the cookie auth it was kinda complicated and i think jwt is the "easiest" way for my case
Unknown User
Unknown User20h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP20h ago
forget about the cookie i just setup identity for UserManager<User>, passwords hashing etc but i don't use cookies anymore
Unknown User
Unknown User20h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP20h ago
yeah it is if Authorization: Bearer <blablaba> header is present and validated
Unknown User
Unknown User20h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP20h ago
aspnet core identity handles jwt ?
Unknown User
Unknown User20h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP20h ago
my main issue right now is not the API the api works fine, IP works fine also [Authorize] controllers cannot be accessed without a valid jwt right i have some issues with the frontend (.Web), clients basically because i think i kinda messed up somewhere hold on i'll push everything
P A T R I C K
P A T R I C KOP20h ago
GitHub
GitHub - kubikpatrick/Poppsza
Contribute to kubikpatrick/Poppsza development by creating an account on GitHub.
P A T R I C K
P A T R I C KOP20h ago
P A T R I C K
P A T R I C KOP19h ago
but it works OH GOD DAMN LOOK AT THAT
P A T R I C K
P A T R I C KOP19h ago
No description
P A T R I C K
P A T R I C KOP19h ago
No description
P A T R I C K
P A T R I C KOP19h ago
DAMN IT IS WOR KING @TeBeCo look at this shit but it only works for the back that's better than nothing but for the front i also want my User.Identity.IsAuthenticated to work
Unknown User
Unknown User19h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
okay i think i got it well the human user is signing in through the web client that will get the account from the api idk if it’s clear
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
no worries ik my explanations arent obvious too
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
no i wont deploy anything
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
Api is self hosted by the users
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
open source shit YES exactly
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
no no i also write clients
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
free open source i don’tplan to earn any money from it
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
i guess they will have some basic IT knowledge like JWT auth, URI binding i mean they’re not supposed to know nothing
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
no no desktop app will just be a WPF client i think they wont have to deploy any clients they can if they want to but it’s not mandatory
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
i mean they will just download the .exe ig idk
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
yeah that’s what i was planning but it’s not for now right
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
3 tokens?
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
yeah that’s what i wanted to do idk i just want to implement that in the best way
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
hmmm what i did actually is JWT for the back right that returns the generated token to the front /auth/login returns a token
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
the front stores it in a cookie
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
well idk i haven’t thought about it yet
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
yeah lmaoo euh first is that done in a correct way?
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
yeah
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
yeah as a cookie
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
yeah mobile is gonna come later okay so at least this is correct
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
this is another issue lmao
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
yeah i know
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
it sounds logical
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP18h ago
i was thinking about a distributed cache like redis
Unknown User
Unknown User18h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP12h ago
for cookies? i mean the app is not meant to be distributed now i focus on a functional auth and later i’ll see how to set everything that up i gotta need to find some map tile provider @TeBeCo okay i have found a solution for my User.Identity.IsAuthenticated and it was pretty easy i just had to setup a cookie auth for my front
Unknown User
Unknown User12h ago
Message Not Public
Sign In & Join Server To View
P A T R I C K
P A T R I C KOP12h ago
yeah that shit is magic my mom's gonna be proud

Did you find this page helpful?