Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

88 строки
2.5KB

  1. using Campaign_Tracker.Server.Authentication;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Mvc;
  4. namespace Campaign_Tracker.Server.Controllers;
  5. [ApiController]
  6. [AllowAnonymous]
  7. [Route("api/auth/token")]
  8. public sealed class AuthTokenController : ControllerBase
  9. {
  10. private readonly IHostEnvironment _environment;
  11. private readonly IKeycloakTokenClient _tokenClient;
  12. public AuthTokenController(
  13. IKeycloakTokenClient tokenClient,
  14. IHostEnvironment environment)
  15. {
  16. _environment = environment;
  17. _tokenClient = tokenClient;
  18. }
  19. [HttpPost("exchange")]
  20. public async Task<ActionResult<AuthTokenSetResponse>> Exchange(
  21. [FromBody] AuthorizationCodeExchangeRequest request,
  22. CancellationToken cancellationToken)
  23. {
  24. if (string.IsNullOrWhiteSpace(request.Code) ||
  25. string.IsNullOrWhiteSpace(request.RedirectUri))
  26. {
  27. return BadRequest();
  28. }
  29. try
  30. {
  31. return Ok(await _tokenClient.ExchangeAuthorizationCodeAsync(
  32. request.Code,
  33. request.RedirectUri,
  34. cancellationToken));
  35. }
  36. catch (KeycloakTokenRequestException exception)
  37. {
  38. return Unauthorized(CreateTokenExchangeProblem(exception));
  39. }
  40. }
  41. [HttpPost("refresh")]
  42. public async Task<ActionResult<AuthTokenSetResponse>> Refresh(
  43. [FromBody] RefreshTokenRequest request,
  44. CancellationToken cancellationToken)
  45. {
  46. if (string.IsNullOrWhiteSpace(request.RefreshToken))
  47. {
  48. return BadRequest();
  49. }
  50. try
  51. {
  52. return Ok(await _tokenClient.RefreshAccessTokenAsync(
  53. request.RefreshToken,
  54. cancellationToken));
  55. }
  56. catch (KeycloakTokenRequestException exception)
  57. {
  58. return Unauthorized(CreateTokenExchangeProblem(exception));
  59. }
  60. }
  61. private object CreateTokenExchangeProblem(KeycloakTokenRequestException exception)
  62. {
  63. if (!_environment.IsDevelopment())
  64. {
  65. return new { error = "Keycloak token request failed." };
  66. }
  67. return new
  68. {
  69. error = "Keycloak token request failed.",
  70. statusCode = (int)exception.StatusCode,
  71. keycloakResponse = exception.ResponseBody,
  72. };
  73. }
  74. }
  75. public sealed record AuthorizationCodeExchangeRequest(string Code, string RedirectUri);
  76. public sealed record RefreshTokenRequest(string RefreshToken);

Powered by TurnKey Linux.