Last active
June 17, 2024 11:37
-
-
Save ep-cc/38669e63bcfb4ab385f83cf69ace997b to your computer and use it in GitHub Desktop.
Dotnet core JWT auth using cookie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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 }); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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