没有为方案“Cookies”注册身份验证处理程序。注册的方案有:Application、Bearer、ASOS

问题描述 投票:0回答:2

我正在使用 .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”计划。注册方案有:申请、承载、 ASOS。你是否忘记打电话 AddAuthentication().AddSomeAuthHandler?

我在这里缺少什么。有什么帮助吗?

asp.net asp.net-core oauth-2.0 asp.net-core-2.0 openid-connect
2个回答
0
投票

所以发现了问题,实际上我在 cookie 方案中使用“应用程序”名称,而在控制器中我使用默认名称“Cookies”。因此只需将显式的“应用程序”名称删除为默认的“Cookies”名称 未指定authenticationScheme,且未找到DefaultChallengeScheme Cookies Authentication


0
投票

就我而言,我在添加身份验证时使用“Cookie”,在调用 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");
    }
© www.soinside.com 2019 - 2024. All rights reserved.