Я работаю над микросервисной архитектурой со следующими проектами: WEB, API и AUTH. Я столкнулся с проблемой в веб-проекте: мне нужно получить токен аутентификации из службы AUTH.
Файл конфигурации веб-проекта:
public async Task OnPost()
{
// check if we are in the context of an authorization request
var context = await _interaction.GetAuthorizationContextAsync(Input.ReturnUrl);
// the user clicked the "cancel" button
if (Input.Button != "login")
{
if (context != null)
{
// This "can't happen", because if the ReturnUrl was null, then the context would be null
ArgumentNullException.ThrowIfNull(Input.ReturnUrl, nameof(Input.ReturnUrl));
// if the user cancels, send a result back into IdentityServer as if they
// denied the consent (even if this client does not require consent).
// this will send back an access denied OIDC error response to the client.
await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied);
// we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
if (context.IsNativeClient())
{
// The client is native, so this change in how to
// return the response is for better UX for the end user.
return this.LoadingPage(Input.ReturnUrl);
}
return Redirect(Input.ReturnUrl ?? "~/");
}
else
{
// since we don't have a valid context, then we just go back to the home page
return Redirect("~/");
}
}
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(
Input.Username, Input.Password, Input.RememberLogin, lockoutOnFailure: false);
if (result.Succeeded)
{
var user = await _users.FindByNameAsync(Input.Username);
await _events.RaiseAsync(
new UserLoginSuccessEvent(user.UserName,
user.Id, user.FirstName + " " + user.LastName,
clientId: context?.Client.ClientId));
if (context != null)
{
return Challenge(new AuthenticationProperties { RedirectUri = "/" }, "oidc");
}
if (Url.IsLocalUrl(Input.ReturnUrl))
{
return Redirect(Input.ReturnUrl);
}
else if (string.IsNullOrEmpty(Input.ReturnUrl))
{
return Redirect("~/");
}
else
{
throw new Exception("Invalid return Url");
}
}
const string error = "invalid credentials";
await _events.RaiseAsync(new UserLoginFailureEvent(Input.Username, error, clientId:context?.Client.ClientId));
ModelState.AddModelError(string.Empty, LoginOptions.InvalidCredentialsErrorMessage);
}
// something went wrong, show form with error
await BuildModelAsync(Input.ReturnUrl);
return Page();
}
И текст ошибки: InvalidOperationException: для схемы «oidc» не зарегистрирован обработчик аутентификации. Зарегистрированные схемы: Identity.Application, Identity.External, Identity.TwoFactorRememberMe, Identity.TwoFactorUserId, idsrv, idsrv.external. Вы забыли вызвать AddAuthentication().AddSomeAuthHandler?
Может кто-нибудь мне с этим помочь?
Мне нужно реализовать обычную авторизацию внутри веб-проекта.
Я работаю над микросервисной архитектурой со следующими проектами: WEB, API и AUTH. Я столкнулся с проблемой в веб-проекте: мне нужно получить токен аутентификации из службы AUTH. Файл конфигурации веб-проекта: [code]Code: using IdentityModel.Client; using Mango.Web; using Mango.Web.Services; using Mango.Web.Services.Interfaces; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.DataProtection; using Microsoft.CodeAnalysis.Options; using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container. builder.Services.AddHttpClient(); ServiceUrls.ProductAPIBase = builder.Configuration["ServiceUrls:ProductAPI"];
options.Events = new OpenIdConnectEvents { OnTokenResponseReceived = async context => { var tokens = context.TokenEndpointResponse; if (tokens != null) { // Установка куки с токеном доступа context.HttpContext.Response.Cookies.Append("access_token", tokens.AccessToken, new CookieOptions { HttpOnly = true, Secure = true, SameSite = SameSiteMode.None, Expires = DateTimeOffset.UtcNow.AddMinutes(10) }); } } }; });
var app = builder.Build();
// Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); }
app.Run(); [/code] Файл конфигурации проекта идентификации [code]using Mango.Services.Identity; using Mango.Services.Identity.Entities; using Mango.Services.Identity.Initializer; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container. builder.Services.AddControllersWithViews();
var initializer = builder.Services.BuildServiceProvider().GetService();
var app = builder.Build();
// Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); }
app.Run(); [/code] Модель страницы проекта идентификации, которая должна вернуть мне токен: [code]public async Task OnPost() { // check if we are in the context of an authorization request var context = await _interaction.GetAuthorizationContextAsync(Input.ReturnUrl);
// the user clicked the "cancel" button if (Input.Button != "login") { if (context != null) { // This "can't happen", because if the ReturnUrl was null, then the context would be null ArgumentNullException.ThrowIfNull(Input.ReturnUrl, nameof(Input.ReturnUrl));
// if the user cancels, send a result back into IdentityServer as if they // denied the consent (even if this client does not require consent). // this will send back an access denied OIDC error response to the client. await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied);
// we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null if (context.IsNativeClient()) { // The client is native, so this change in how to // return the response is for better UX for the end user. return this.LoadingPage(Input.ReturnUrl); }
return Redirect(Input.ReturnUrl ?? "~/"); } else { // since we don't have a valid context, then we just go back to the home page return Redirect("~/"); } }
if (ModelState.IsValid) { var result = await _signInManager.PasswordSignInAsync( Input.Username, Input.Password, Input.RememberLogin, lockoutOnFailure: false); if (result.Succeeded) { var user = await _users.FindByNameAsync(Input.Username);
// something went wrong, show form with error await BuildModelAsync(Input.ReturnUrl); return Page(); } [/code] И текст ошибки: [b]InvalidOperationException: для схемы «oidc» не зарегистрирован обработчик аутентификации. Зарегистрированные схемы: Identity.Application, Identity.External, Identity.TwoFactorRememberMe, Identity.TwoFactorUserId, idsrv, idsrv.external. Вы забыли вызвать AddAuthentication().AddSomeAuthHandler?[/b] Может кто-нибудь мне с этим помочь? Мне нужно реализовать обычную авторизацию внутри веб-проекта.
Я переношу устаревшее приложение ASP.Net для поддержки аутентификации OpenId Connect с помощью поставщика удостоверений Keycloak. Для этого я использовал промежуточное ПО OWIN OpenId, и оно работает, но теперь мне нужно реализовать управление...
Я следую информации из этого видео Ника Чапсаса на YouTube.
У меня есть следующие настройки, как описано:
API
builder.Services.AddAuthentication(a =>
{
a.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
a.DefaultChallengeScheme...
Я следую информации из этого видео Ника Чапсаса на YouTube.
У меня есть следующие настройки, как описано:
API
builder.Services.AddAuthentication(a =>
{
a.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
a.DefaultChallengeScheme...
Я работаю над оберткой функции из многоплатформенной кодовой базы Kotlin (KMP) в Swift. Хотя моя текущая реализация работает, она кажется довольно многословной и шаблонной. Я ищу более элегантное, компактное и идиоматическое решение на Swift.
Вот...
Я работаю над оберткой функции из многоплатформенной кодовой базы Kotlin (KMP) в Swift. Хотя моя текущая реализация работает, она кажется довольно многословной и шаблонной. Я ищу более элегантное, компактное и идиоматическое решение на Swift.
Вот...