Advertisement
Guest User

Untitled

a guest
Nov 14th, 2024
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | Software | 0 0
  1. using Microsoft.AspNetCore.Http;
  2. using OpenIddict.Abstractions;
  3. using OpenIddict.Server;
  4. using System.Net;
  5.  
  6. namespace Company.WebApi.CustomToken;
  7.  
  8. public class CustomTokenEndpointHandler(IHttpContextAccessor httpContextAccessor)
  9. : IOpenIddictServerHandler<OpenIddictServerEvents.ApplyTokenResponseContext>
  10. {
  11. private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor;
  12.  
  13. public ValueTask HandleAsync(OpenIddictServerEvents.ApplyTokenResponseContext context)
  14. {
  15. if (context.Request != null)
  16. {
  17. var request = context.Request.ClientId;
  18.  
  19. if (request != "logistic_petrus_react_client")
  20. {
  21. return ValueTask.CompletedTask;
  22. }
  23. }
  24. else
  25. {
  26. throw new NullReferenceException("Отстутствует Request");
  27. }
  28.  
  29. var response = context.Transaction.Response;
  30.  
  31. var refreshToken = response?.GetParameter(OpenIddictConstants.Parameters.RefreshToken)?.ToString();
  32.  
  33. var accessToken = response?.GetParameter(OpenIddictConstants.Parameters.AccessToken)?.ToString();
  34.  
  35.  
  36. if (!string.IsNullOrEmpty(refreshToken) && !string.IsNullOrEmpty(accessToken))
  37. {
  38.  
  39.  
  40. if (_httpContextAccessor.HttpContext != null)
  41. {
  42. var cookieOptions = new CookieOptions
  43. {
  44. HttpOnly = true,
  45. Secure = true,
  46. //IsEssential = true,
  47. SameSite = SameSiteMode.None,
  48.  
  49. Expires = DateTimeOffset.UtcNow.AddDays(14),
  50. Path = "/",
  51.  
  52. };
  53.  
  54. _httpContextAccessor.HttpContext.Response.Cookies.Append("refresh_token", refreshToken, cookieOptions);
  55. _httpContextAccessor.HttpContext.Response.Cookies.Append("access_token", accessToken, cookieOptions);
  56.  
  57. Console.WriteLine(1);
  58. }
  59. else
  60. {
  61. throw new NullReferenceException("Отстутствует httpContext");
  62. }
  63.  
  64. if (response != null)
  65. {
  66. response.RemoveParameter(OpenIddictConstants.Parameters.RefreshToken);
  67. response.RemoveParameter(OpenIddictConstants.Parameters.AccessToken);
  68. }
  69. else
  70. {
  71. throw new NullReferenceException("Отстутствует response");
  72. }
  73. }
  74.  
  75. return ValueTask.CompletedTask;
  76. }
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement