|
2 | 2 | using Flowboard_Project_Management_System_Backend.Services; |
3 | 3 | using MongoDB.Driver; |
4 | 4 | using Microsoft.IdentityModel.Tokens; |
| 5 | +using Microsoft.AspNetCore.Http; |
5 | 6 | using System.IdentityModel.Tokens.Jwt; |
6 | 7 | using System.Security.Claims; |
7 | 8 | using System.Text; |
|
13 | 14 | public class PublicController : ControllerBase |
14 | 15 | { |
15 | 16 | private readonly MongoDbService _mongoDbService; |
| 17 | + private readonly IHostEnvironment _env; |
16 | 18 |
|
17 | | - public PublicController(MongoDbService mongoDbService) |
| 19 | + public PublicController(MongoDbService mongoDbService, IHostEnvironment environment) |
18 | 20 | { |
19 | 21 | _mongoDbService = mongoDbService; |
| 22 | + _env = environment; |
20 | 23 | } |
21 | 24 |
|
22 | 25 | [HttpPost("register")] |
@@ -79,14 +82,44 @@ public IActionResult Login([FromBody] FlowModels.LoginRequest loginRequest) |
79 | 82 | // Generate JWT token |
80 | 83 | var token = GenerateJwtToken(user); |
81 | 84 |
|
| 85 | + // Set JWT as HttpOnly cookie for automatic browser authentication |
| 86 | + var expiryMinutes = int.Parse(Environment.GetEnvironmentVariable("JWT_EXPIRY_MINUTES") ?? "60"); |
| 87 | + var cookieOptions = new CookieOptions |
| 88 | + { |
| 89 | + HttpOnly = true, |
| 90 | + Secure = !_env.IsDevelopment(), // Secure cookie in production |
| 91 | + SameSite = _env.IsDevelopment() ? SameSiteMode.Lax : SameSiteMode.None, |
| 92 | + Expires = DateTime.UtcNow.AddMinutes(expiryMinutes), |
| 93 | + Path = "/" |
| 94 | + }; |
| 95 | + |
| 96 | + Response.Cookies.Append("jwt", token, cookieOptions); |
| 97 | + |
82 | 98 | return Ok(new |
83 | 99 | { |
84 | 100 | message = "Login successful!", |
85 | 101 | user, |
86 | | - token |
| 102 | + |
87 | 103 | }); |
88 | 104 | } |
89 | 105 |
|
| 106 | + [HttpPost("logout")] |
| 107 | + public IActionResult Logout() |
| 108 | + { |
| 109 | + // Remove cookie by setting expired options |
| 110 | + var cookieOptions = new CookieOptions |
| 111 | + { |
| 112 | + HttpOnly = true, |
| 113 | + // Secure = !_env.IsDevelopment(), |
| 114 | + Secure = _env.IsDevelopment(), |
| 115 | + SameSite = _env.IsDevelopment() ? SameSiteMode.Lax : SameSiteMode.None, |
| 116 | + Expires = DateTime.UtcNow.AddDays(-1), |
| 117 | + Path = "/" |
| 118 | + }; |
| 119 | + Response.Cookies.Delete("jwt", cookieOptions); |
| 120 | + return Ok(new { message = "Logout successful" }); |
| 121 | + } |
| 122 | + |
90 | 123 | // ---------------- JWT Helper ---------------- |
91 | 124 | private string GenerateJwtToken(FlowModels.User user) |
92 | 125 | { |
|
0 commit comments