wasAsked.

How do you carry out authentication from client using JWT token and than authentication with server?

Wipro · Role not specified · technical

Published

Year not specified · C#, Authentication & Security

Community answers

Posted by wasAsked editorial collection

The client obtains a JWT once by authenticating, then sends it with every request; the server validates it each time. Step 1 — The client authenticates POST /api/auth/login with username and password (over HTTPS), or the client signs in through an identity provider (OpenID Connect). Step 2 — The server verifies credentials and issues tokens - Verifies the password hash (ASP.NET Core Identity's PasswordHasher or a similar algorithm), checks lockout and MFA. - Creates a signed JWT access token with claims (sub, email, roles, iss, aud, exp) and a refresh token stored server-side. - Returns them to the client. Step 3 — The client stores and sends the token For a C# client (another service, desktop or MAUI app): var login = await http.PostAsJsonAsync("api/auth/login", new { username, password }, ct); login.EnsureSuccessStatusCode(); var tokens = await login.Content.ReadFromJsonAsync<TokenResponse>(ct); http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokens!.AccessToken); var orders = await http.GetFromJsonAsync<List<OrderDto>>("api/orders", ct); Better: a DelegatingHandler that adds the header and refreshes the token automatically when it expires, registered with IHttpClientFactory. Browser apps use an interceptor and secure storage (or a BFF with cookies). Step 4 — The server authenticates each request builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(o => o.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = cfg["Jwt:Issuer"], ValidAudience = cfg["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(cfg["Jwt:Key"]!)), ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true }); app.UseAuthentication(); app.UseAuthorization(); The JwtBearer handler reads the Authorization header, verifies the signature, issuer, audience and expiry, and sets HttpContext.User. Step 5 — Authorization [Authorize] and policies ([Authorize(Roles = "Admin")]) decide access; resource checks ensure users only access their own data. Step 6 — Expiry On 401, the client uses the refresh token at /api/auth/refresh to get a new access token, then retries. Security notes: HTTPS only, short-lived access tokens, keys in Key Vault, no sensitive data in claims, and never logging tokens.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics