InvalidOperationException:没有为方案Bearer注册任何身份验证处理程序. [英] InvalidOperationException: No authentication handler is registered for the scheme Bearer.

查看:539
本文介绍了InvalidOperationException:没有为方案Bearer注册任何身份验证处理程序.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用.net core 2.1实现Aspnet.security.openidconnect(ASOS),我可以使用ASOS成功生成access_token和refreshtoken,但是当我在任何操作上添加Authorize Attribute并尝试使用邮递员调用该操作时我收到以下异常:

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:

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

这是代码:

 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();

这里缺少什么?谢谢

推荐答案

您共享的摘录仅生成令牌:它不会验证令牌.要启用令牌验证,请参考 AspNet.Security.OAuth.Validation 包并注册aspnet-contrib验证处理程序:

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:

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

这篇关于InvalidOperationException:没有为方案Bearer注册任何身份验证处理程序.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆