简体   繁体   English

InvalidOperationException:没有为方案承载注册身份验证处理程序。

[英]InvalidOperationException: No authentication handler is registered for the scheme Bearer.

I am trying to implement Aspnet.security.openidconnect (ASOS) with .net core 2.1 I can successfully generate access_token and refreshtoken using ASOS but when I am adding Authorize Attribute on any of my action and try to call that action with postman I am getting following exception:我正在尝试使用 .net core 2.1 实现 Aspnet.security.openidconnect (ASOS) 我可以使用 ASOS 成功生成 access_token 和 refreshtoken 但是当我在我的任何操作上添加授权属性并尝试使用邮递员调用该操作时,我得到了以下异常:

InvalidOperationException: No authentication handler is registered for the scheme Bearer. The registered schemes are: ASOS. Did you forget to call AddAuthentication().Add[SomeAuthHandler

Here is the code:这是代码:

 services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddOpenIdConnectServer(options =>
    {
        options.AuthorizationEndpointPath = "/connect/authorize";
        // Enable the token endpoint.
        options.TokenEndpointPath = "/connect/token";

        // 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.IsRefreshTokenGrantType())
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.UnsupportedGrantType,
                    description: "Only grant_type=password and refresh_token " +
                                 "requests are accepted by this server.");

                return Task.CompletedTask;
            }

            // Note: you can skip the request validation when the client_id
            // parameter is missing to support unauthenticated token requests.
            // if (string.IsNullOrEmpty(context.ClientId))
            // {
            //     context.Skip();
            // 
            //     return Task.CompletedTask;
            // }

            // Note: to mitigate brute force attacks, you SHOULD strongly consider applying
            // a key derivation function like PBKDF2 to slow down the secret validation process.
            // You SHOULD also consider using a time-constant comparer to prevent timing attacks.
            if (string.Equals(context.ClientId, "client_id", StringComparison.Ordinal) &&
                string.Equals(context.ClientSecret, "client_secret", StringComparison.Ordinal))
            {
                context.Validate();
            }

            // Note: if Validate() is not explicitly called,
            // the request is automatically rejected.
            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())
            {
                // Implement context.Request.Username/context.Request.Password validation here.
                // Note: you can call context Reject() to indicate that authentication failed.
                // Using password derivation and time-constant comparer is STRONGLY recommended.
                //if (!string.Equals(context.Request.Username, "Bob", StringComparison.Ordinal) ||
                //    !string.Equals(context.Request.Password, "P@ssw0rd", StringComparison.Ordinal))
                //{
                //    context.Reject(
                //        error: OpenIdConnectConstants.Errors.InvalidGrant,
                //        description: "Invalid user credentials.");

                //    return Task.CompletedTask;
                //}

                var identity = new ClaimsIdentity(context.Scheme.Name,
                    OpenIdConnectConstants.Claims.Name,
                    OpenIdConnectConstants.Claims.Role);

                // Add the mandatory subject/user identifier claim.
                identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "[unique id]");

                // 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("urn:customclaim", "value",
                    OpenIdConnectConstants.Destinations.AccessToken,
                    OpenIdConnectConstants.Destinations.IdentityToken);

                var ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identity),
                    new 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;
        };
    });

and in configure method I am calling:在我调用的配置方法中:

app.UseAuthentication();

What is missing here?这里缺少什么? Thanks谢谢

The snippet you shared only generates tokens: it doesn't validate them.您共享的代码段仅生成令牌:它不会验证它们。 To enable token validation, reference the AspNet.Security.OAuth.Validation package and register the aspnet-contrib validation handler:要启用令牌验证,请参考AspNet.Security.OAuth.Validation包并注册 aspnet-contrib 验证处理程序:

services.AddAuthentication(OAuthValidationDefaults.AuthenticationScheme)
    .AddOAuthValidation();

.NET Core 3.1 with JWT Authentication .NET Core 3.1 与 JWT 身份验证

 services.AddAuthentication(option =>
    {
        option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(option =>
    {
        option.SaveToken = true;
        option.TokenValidationParameters = new TokenValidationParameters
        {
            SaveSigninToken = true,
            ValidateIssuer = true,
            ValidateAudience = false,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = Configuration["Jwt:Issuer"],       // Jwt:Issuer - config value 
            ValidAudience = Configuration["Jwt:Issuer"],     // Jwt:Issuer - config value 
            IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) // Jwt:Key - config value 
        };
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 没有为方案“Cookies”注册身份验证处理程序。 注册的方案有:Application、Bearer、ASOS - No authentication handler is registered for the scheme 'Cookies'. The registered schemes are: Application, Bearer, ASOS 没有配置身份验证处理程序来处理该方案 - No authentication handler is configured to handle the scheme 没有配置身份验证处理程序来处理该方案:自动 - No authentication handler is configured to handle the scheme: Automatic 没有配置身份验证处理程序来验证该方案:Microsoft.AspNet.Identity.External - No authentication handler is configured to authenticate for the scheme: Microsoft.AspNet.Identity.External ASP.NET Core 2 没有配置身份验证处理程序来处理方案 - ASP.NET Core 2 No authentication handler is configured to handle the scheme Signalr 承载令牌身份验证 - Signalr Bearer token authentication 身份验证失败-System.InvalidOperationException - Authentication failed - System.InvalidOperationException ASP.NET 4.7.2 OWIN JWT 承载身份验证承载前缀 - ASP.NET 4.7.2 OWIN JWT Bearer Authentication Bearer prefix System.InvalidOperationException:'SQLBASEOLEDB.1'提供程序未在本地计算机上注册 - System.InvalidOperationException: 'SQLBASEOLEDB.1' provider not registered on local machine Web API安全和身份验证 - 承载令牌 - Web API Security and Authentication - bearer token
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM