asp.net - 没有为方案“Cookies”注册身份验证处理程序。注册的方案有:Application、Bearer、ASOS
问题描述
我正在使用 .net core 2.1 应用程序实现 Aspnet.security.openidconnect (ASOS)。现在的问题是当我试图在控制器中执行这个块时,
public async Task<IActionResult> Authorize()
{
if (Response.StatusCode != 200)
{
return View("AuthorizeError");
}
var ticket = await AuthenticationHttpContextExtensions.AuthenticateAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme);
var identity = ticket != null && ticket.Principal != null ? ticket.Ticket.Principal : null;
if (identity == null)
{
await AuthenticationHttpContextExtensions.ChallengeAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, null);
return Unauthorized();
}
ViewData["Name"] = ticket.Principal.Identity.Name;
var scopes = (HttpContext.Request.Query["scope"].ToString() ?? "").Split(' ');
ViewData["Scopes"] = scopes;
//var claimsIdentity = new ClaimsIdentity(identity.Claims, "Bearer", identity.NameClaimType, identity.RoleClaimType);
var claimsIdentity = new ClaimsIdentity(identity.Claims, "Bearer");
foreach (var scope in scopes)
{
claimsIdentity.AddClaim(new Claim("urn:oauth:scope", scope));
}
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, claimsPrincipal);
logger.Info("Authorize request received");
return View();
}
我在这条线上遇到的错误:
var ticket = await AuthenticationHttpContextExtensions.AuthenticateAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme);
这是 ASOS 在启动时的实现:
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie("Application", options =>
{
options.LoginPath = new PathString(LoginPath);
options.LogoutPath = new PathString(LogoutPath);
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
//options.AccessDeniedPath = new PathString();
});
//services.AddAuthentication("External")
// .AddCookie("Cookies", options =>
// {
// options.Cookie.Name = CookieAuthenticationDefaults.CookiePrefix + "External";
// options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
// });
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
services.AddAuthentication(OAuthValidationDefaults.AuthenticationScheme).AddOAuthValidation()
.AddOpenIdConnectServer(options =>
{
options.AuthorizationEndpointPath = new PathString(AuthorizePath);
// Enable the token endpoint.
options.TokenEndpointPath = new PathString(TokenPath);
options.ApplicationCanDisplayErrors = true;
options.AccessTokenLifetime = TimeSpan.FromMinutes(5);
#if DEBUG
options.AllowInsecureHttp = true;
#endif
options.Provider.OnValidateAuthorizationRequest = context =>
{
if (string.Equals(context.ClientId, Configuration["OpenIdServer:ClientId"], StringComparison.Ordinal))
{
context.Validate(context.RedirectUri);
}
return Task.CompletedTask;
};
// Implement OnValidateTokenRequest to support flows using the token endpoint.
options.Provider.OnValidateTokenRequest = context =>
{
// Reject token requests that don't use grant_type=password or grant_type=refresh_token.
if (!context.Request.IsClientCredentialsGrantType() && !context.Request.IsPasswordGrantType()
&& !context.Request.IsRefreshTokenGrantType())
{
context.Reject(
error: OpenIdConnectConstants.Errors.UnsupportedGrantType,
description: "Only grant_type=password and refresh_token " +
"requests are accepted by this server.");
return Task.CompletedTask;
}
if (string.IsNullOrEmpty(context.ClientId))
{
context.Skip();
return Task.CompletedTask;
}
if (string.Equals(context.ClientId, Configuration["OpenIdServer:ClientId"], StringComparison.Ordinal) &&
string.Equals(context.ClientSecret, Configuration["OpenIdServer:ClientSecret"], StringComparison.Ordinal))
{
context.Validate();
}
return Task.CompletedTask;
};
// Implement OnHandleTokenRequest to support token requests.
options.Provider.OnHandleTokenRequest = context =>
{
// Only handle grant_type=password token requests and let
// the OpenID Connect server handle the other grant types.
if (context.Request.IsClientCredentialsGrantType() || context.Request.IsPasswordGrantType())
{
//var identity = new ClaimsIdentity(context.Scheme.Name,
// OpenIdConnectConstants.Claims.Name,
// OpenIdConnectConstants.Claims.Role);
ClaimsIdentity identity = null;
if (context.Request.IsClientCredentialsGrantType())
{
identity = new ClaimsIdentity(new GenericIdentity(context.Request.ClientId, "Bearer"), context.Request.GetScopes().Select(x => new Claim("urn:oauth:scope", x)));
}
else if (context.Request.IsPasswordGrantType())
{
identity = new ClaimsIdentity(new GenericIdentity(context.Request.Username, "Bearer"), context.Request.GetScopes().Select(x => new Claim("urn:oauth:scope", x)));
}
// Add the mandatory subject/user identifier claim.
// By default, claims are not serialized in the access/identity tokens.
// Use the overload taking a "destinations" parameter to make sure
// your claims are correctly inserted in the appropriate tokens.
identity.AddClaim(OpenIdConnectConstants.Claims.Subject, Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"), OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken);
var ticket = new Microsoft.AspNetCore.Authentication.AuthenticationTicket(
new ClaimsPrincipal(identity),
new Microsoft.AspNetCore.Authentication.AuthenticationProperties(),
context.Scheme.Name);
// Call SetScopes with the list of scopes you want to grant
// (specify offline_access to issue a refresh token).
ticket.SetScopes(
OpenIdConnectConstants.Scopes.Profile,
OpenIdConnectConstants.Scopes.OfflineAccess);
context.Validate(ticket);
}
return Task.CompletedTask;
};
现在我得到的错误是:
InvalidOperationException:没有为方案“Cookies”注册身份验证处理程序。注册的方案有:Application、Bearer、ASOS。您是否忘记调用 AddAuthentication().AddSomeAuthHandler?
我在这里想念什么。有什么帮助吗?
解决方案
就我而言,我在添加身份验证时使用“Cookies”,在调用 SiginOut 方法时使用“Cookie”。将两个地方都更改为使用“Cookies”
启动:
services.AddAuthentication(config => {
config.DefaultScheme = "Cookies";
config.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")<---- Change here.
.AddOpenIdConnect("oidc", config => {
config.Authority = "https://localhost:44392/";
config.ClientId = "client_id_mvc";
config.ClientSecret = "client_secret_mvc";
config.SaveTokens = true;
config.ResponseType = "code";
//config.SignedOutCallbackPath = "/Privacy";
});
呼叫注销:
public async Task<IActionResult> OnPostAsync()
{
return SignOut("Cookies", "oidc");
}
推荐阅读
- pine-script - 绘制自定义数据 - 每日 = 正常,每周 = 不正常
- python - 使用下拉小部件,从一列中选择值,从数据框中的另一列返回值
- tensorflow - TypeError:“int”对象不可下标(imblearn 生成器)
- dataframe - Pyspark 获取每天的最后一个日期时间
- webrtc - 第二个 RTCPeerConnection 卡在“正在连接”状态,而第一个连接成功连接
- android - bindCameraUseCases() 的回调
- javascript - 有没有办法在没有机器人的情况下在 node.js 中接收电报消息?
- sql-server - SSMS 18 和 VS Community 2019 未识别 SSIS 已安装
- google-cloud-platform - Google Cloud Platform 上的 API 管理
- java - 从邻接列表中删除边缘