Guest User

Untitled

a guest
Apr 20th, 2024
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.64 KB | Source Code | 0 0
  1. ******************this is a part of the service for the controller:
  2.  
  3. public async Task<bool> Login(LoginUserModel user)
  4. {
  5. var identityUser = await _userManager.FindByNameAsync(user.UserName!);
  6. if (identityUser is null)
  7. {
  8. return false;
  9. }
  10.  
  11. return await _userManager.CheckPasswordAsync(identityUser, user.Password!);
  12. }
  13. public string GenerateTokenString(LoginUserModel user)
  14. {
  15. var tokenId = Guid.NewGuid().ToString(); // Unique identifier for each token
  16.  
  17. var claims = new List<Claim>
  18. {
  19. new Claim(ClaimTypes.NameIdentifier, user.UserName !),
  20. new Claim(ClaimTypes.Role, "Admin"), // This should be dynamic based on actual user role
  21. new Claim("TokenId", tokenId) // Include the unique TokenId in the token
  22. };
  23.  
  24. var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]!));
  25. var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha512Signature);
  26.  
  27. var tokenDescriptor = new SecurityTokenDescriptor
  28. {
  29. Subject = new ClaimsIdentity(claims),
  30. Expires = DateTime.UtcNow.AddMinutes(60), // Token validity period
  31. Issuer = _config["Jwt:Issuer"],
  32. Audience = _config["Jwt:Audience"],
  33. SigningCredentials = signingCredentials
  34.  
  35. };
  36.  
  37. var tokenHandler = new JwtSecurityTokenHandler();
  38. var token = tokenHandler.CreateToken(tokenDescriptor);
  39.  
  40. return tokenHandler.WriteToken(token);
  41. }
  42. public async Task<string> GenerateRefreshToken(string userName)
  43. {
  44. var user = await _userManager.FindByNameAsync(userName);
  45. if (user == null) return null!;
  46.  
  47. // Create a new refresh token
  48. var refreshToken = Convert.ToBase64String(RandomNumberGenerator.GetBytes(64));
  49. user.RefreshToken = refreshToken;
  50. user.RefreshTokenExpiryTime = DateTime.UtcNow.AddDays(14); // Set refresh token validity
  51.  
  52. await _userManager.UpdateAsync(user);
  53.  
  54. return refreshToken;
  55. }
  56.  
  57. ***************************this is the program.cs:
  58.  
  59. using EasyLink.Server.Database.Context;
  60. using EasyLink.Server.Identity;
  61. using EasyLink.Server.Services.Auth;
  62. using EasyLink.Server.Services.Categories;
  63. using EasyLink.Server.Services.Stripe;
  64. using Microsoft.AspNetCore.Authentication.JwtBearer;
  65. using Microsoft.AspNetCore.Identity;
  66. using Microsoft.EntityFrameworkCore;
  67. using Microsoft.IdentityModel.Tokens;
  68. using Stripe;
  69. using System.Text;
  70.  
  71. var builder = WebApplication.CreateBuilder(args);
  72.  
  73. // Add services to the container.
  74. builder.Services.AddControllers();
  75. builder.Services.AddEndpointsApiExplorer();
  76. builder.Services.AddSwaggerGen();
  77. builder.Services.AddHttpClient();
  78.  
  79. // Configure DbContext.
  80. builder.Services.AddDbContext<AuthDbContext>(options =>
  81. options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
  82.  
  83. // Configure Identity.
  84. builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
  85. {
  86. options.Password.RequiredLength = 8;
  87. options.Password.RequireLowercase = true;
  88. options.Password.RequireUppercase = true;
  89. options.Password.RequireDigit = true;
  90. options.Password.RequireNonAlphanumeric = false;
  91. }).AddEntityFrameworkStores<AuthDbContext>()
  92. .AddDefaultTokenProviders();
  93.  
  94. // Configure JWT Authentication.
  95. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  96. .AddJwtBearer(options =>
  97. {
  98. options.TokenValidationParameters = new TokenValidationParameters
  99. {
  100. ValidateIssuer = true,
  101. ValidateAudience = true,
  102. ValidateLifetime = true,
  103. ValidateIssuerSigningKey = true,
  104. ValidIssuer = builder.Configuration["Jwt:Issuer"],
  105. ValidAudience = builder.Configuration["Jwt:Audience"],
  106. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!)),
  107. ClockSkew = TimeSpan.Zero
  108. };
  109. options.Events = new JwtBearerEvents
  110. {
  111. OnAuthenticationFailed = context =>
  112. {
  113. Console.WriteLine("\n\n\n\n\n\n\nAuthentication failed: " + context.Exception.Message);
  114. return Task.CompletedTask;
  115. },
  116. OnTokenValidated = context =>
  117. {
  118. Console.WriteLine("\n\n\n\n\n\n\nToken validated successfully.");
  119. return Task.CompletedTask;
  120. },
  121. OnMessageReceived = context =>
  122. {
  123. Console.WriteLine("\n\n\n\nerror\n\n\n");
  124. if (context.Request.Cookies.ContainsKey("AccessToken"))
  125. {
  126. context.Token = context.Request.Cookies["AccessToken"];
  127. }
  128. return Task.CompletedTask;
  129. }
  130. };
  131. });
  132.  
  133. // Additional services.
  134. builder.Services.AddTransient<IAuthService, AuthService>();
  135. builder.Services.AddScoped<IStripeService, StripeService>();
  136. builder.Services.AddHttpClient("CategoryApiClient", client =>
  137. {
  138. client.BaseAddress = new Uri("https://www.autovit.ro/api/");
  139. client.DefaultRequestHeaders.Add("Accept", "application/json");
  140. });
  141. builder.Services.AddScoped<ICategoriesService, CategoriesService>();
  142. builder.Services.AddCors(options =>
  143. {
  144. options.AddPolicy("AllowSpecificOrigin", builder =>
  145. {
  146. builder.WithOrigins("https://localhost:5173")
  147. .AllowAnyHeader()
  148. .AllowAnyMethod()
  149. .AllowCredentials();
  150. });
  151. });
  152. StripeConfiguration.ApiKey = builder.Configuration["Stripe:Key"];
  153.  
  154. var app = builder.Build();
  155.  
  156. // Middleware pipeline configuration.
  157. app.UseDefaultFiles();
  158. app.UseStaticFiles();
  159. app.UseHsts();
  160. app.UseCors("AllowSpecificOrigin");
  161. if (app.Environment.IsDevelopment())
  162. {
  163. app.UseSwagger();
  164. app.UseSwaggerUI();
  165. }
  166. app.UseHttpsRedirection();
  167. app.UseAuthentication();
  168. app.UseAuthorization();
  169. app.MapControllers();
  170. app.MapFallbackToFile("/index.html");
  171. app.Run();
  172.  
  173.  
  174. ***************************************this is a part of the authcontroller:
  175. [HttpPost("Login")]
  176. public async Task<IActionResult> Login([FromBody] LoginUserModel user)
  177. {
  178. if (!ModelState.IsValid)
  179. {
  180. return BadRequest();
  181. }
  182. if (!await _authService.CheckPayment(user.UserName!))
  183. {
  184. return Unauthorized("Payment required.");
  185. }
  186. if (await _authService.Login(user))
  187. {
  188. var tokenString = _authService.GenerateTokenString(user);
  189. var refreshToken = await _authService.GenerateRefreshToken(user.UserName!);
  190.  
  191. // Store access token and refresh token in HttpOnly cookies
  192. var cookieOptions = new CookieOptions
  193. {
  194. HttpOnly = true,
  195. Secure = true,
  196. SameSite = SameSiteMode.Strict,
  197. Expires = DateTime.UtcNow.AddMinutes(60)
  198. };
  199.  
  200. Response.Cookies.Append("AccessToken", tokenString, cookieOptions);
  201.  
  202. // Extend the cookie's expiry for refresh token since it should be valid longer than access token
  203. var refreshCookieOptions = new CookieOptions
  204. {
  205. HttpOnly = true,
  206. Secure = true,
  207. SameSite = SameSiteMode.Strict,
  208. Expires = DateTime.UtcNow.AddDays(14) // Refresh token validity
  209. };
  210. Response.Cookies.Append("RefreshToken", refreshToken, refreshCookieOptions);
  211.  
  212. return Ok(new { message = "Login successful", accessToken = tokenString, refreshToken = refreshToken });
  213. }
  214.  
  215. return Forbid("Invalid credentials.");
  216. }
  217.  
  218.  
  219. [HttpGet("verify")]
  220. public IActionResult Verify()
  221. {
  222. var isAuthenticated = User.Identity!.IsAuthenticated;
  223.  
  224. return Ok(new { isAuthenticated });
  225. }
  226.  
Add Comment
Please, Sign In to add comment