Я использую OpenIddict для реализации аутентификации и авторизации в моем IdentityServer, и мне нужно вставить access_token иrefresh_token в файлы cookie. У меня есть класс, который расширяет IOpenIddictServerHandler. В этом классе я перехватываю токены и пытаюсь поместить их в файлы cookie, а затем удалить их из тела ответа. Но в куки они не проставляются, ничего не происходит, но удаление проходит успешно. IdentityServer используется с реагирующим клиентом и API
Код CustomTokenEndpointHandler:
using OpenIddict.Abstractions;
using OpenIddict.Server;
namespace Company.WebApi.CustomToken;
public class CustomTokenEndpointHandler : IOpenIddictServerHandler
{
private readonly IHttpContextAccessor _httpContextAccessor;
public CustomTokenEndpointHandler(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public async ValueTask HandleAsync(OpenIddictServerEvents.HandleTokenRequestContext context)
{
if (context.Request == null)
{
throw new NullReferenceException("Request missing in HandleTokenRequestContext");
}
var clientId = context.Request.ClientId;
if (clientId != "logistic_company_react_client")
{
await ValueTask.CompletedTask;
return;
}
var accessToken = context.Transaction.Response?.GetParameter(OpenIddictConstants.Parameters.AccessToken)?.ToString();
var refreshToken = context.Transaction.Response?.GetParameter(OpenIddictConstants.Parameters.RefreshToken)?.ToString();
_httpContextAccessor.HttpContext.Response.OnStarting(() =>
{
if (!string.IsNullOrEmpty(accessToken))
{
_httpContextAccessor.HttpContext.Response.Cookies.Append("access_token", accessToken, new CookieOptions
{
HttpOnly = true,
Secure = false,
SameSite = SameSiteMode.Lax,
Expires = DateTimeOffset.UtcNow.AddHours(1)
});
}
if (!string.IsNullOrEmpty(refreshToken))
{
_httpContextAccessor.HttpContext.Response.Cookies.Append("refresh_token", refreshToken, new CookieOptions
{
HttpOnly = true,
Secure = false,
SameSite = SameSiteMode.Lax,
Expires = DateTimeOffset.UtcNow.AddDays(7)
});
}
context.Transaction.Response?.RemoveParameter(OpenIddictConstants.Parameters.AccessToken);
context.Transaction.Response?.RemoveParameter(OpenIddictConstants.Parameters.RefreshToken);
return Task.CompletedTask;
});
await ValueTask.CompletedTask;
}
}
Фрагмент подключения кода обработчика событий:
services.AddHttpContextAccessor();
services.AddOpenIddict()
.AddServer(options =>
{
options.AddEventHandler(
builder => builder.UseScopedHandler());
...
}
Метод получения токена:
[HttpPost("~/connect/token")]
public async Task Exchange(CancellationToken cancellationToken)
{
var request = HttpContext.GetOpenIddictServerRequest();
if (request is null)
{
return Problem(ApplicationErrors.SpecifiedGrantTypeNotSupported.Name);
}
if (request.IsAuthorizationCodeGrantType() || request.IsRefreshTokenGrantType())
{
ClaimsPrincipal claimsPrincipal = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal;
var command = new TokenQuery(claimsPrincipal, request);
var result = await _sender.Send(command, cancellationToken); //here i get ClaimsIdentity
if (result.IsFailure && result.Error.Code == "User.CannotFindUserFromToken")
{
return Forbid(
authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
properties: new AuthenticationProperties(new Dictionary
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidGrant,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = result.Error.Name
}));
}
return SignIn(new ClaimsPrincipal(result.Value.ClaimsIdentity), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
throw new InvalidOperationException("The specified grant type is not supported.");
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... nidconnect
Как вставить токены в куки в OpenIdConnect ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Сопоставление ролей OpenIDConnect с конфигурацией MediaWiki PluggableAuth
Anonymous » » в форуме Php - 0 Ответы
- 11 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Истечение срока действия схемы аутентификации файлов cookie AspNetCore OpenIdConnect
Anonymous » » в форуме C# - 0 Ответы
- 16 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Истечение срока действия схемы аутентификации файлов cookie AspNetCore OpenIdConnect
Anonymous » » в форуме C# - 0 Ответы
- 17 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Истечение срока действия схемы аутентификации файлов cookie AspNetCore OpenIdConnect
Anonymous » » в форуме C# - 0 Ответы
- 14 Просмотры
-
Последнее сообщение Anonymous
-