Skip to content

Instantly share code, notes, and snippets.

@ep-cc
Last active June 17, 2024 11:37
Show Gist options
  • Save ep-cc/38669e63bcfb4ab385f83cf69ace997b to your computer and use it in GitHub Desktop.
Save ep-cc/38669e63bcfb4ab385f83cf69ace997b to your computer and use it in GitHub Desktop.
Dotnet core JWT auth using cookie
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRquest login)
{
try
{
var user = await _userService.AuthenticateUser(login);
var token = GenerateToken(user);
// This is the extra step
HttpContext.Response.Cookies.Append("access_token", token, new CookieOptions{HttpOnly = true});
// We can also return the user info in the response body
return Ok();
}
catch (Exception e)
{
return BadRequest(new { message = e.Message });
}
}
// Read the token value from the cookie
void AddAuthentication()
{
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ClockSkew = TimeSpan.Zero,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])
),
};
options.Events = new JwtBearerEvents()
{
OnMessageReceived = ctx =>
{
ctx.Token = ctx.Request.Cookies["access_token"];
return Task.CompletedTask;
}
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment