没有指定authenticationScheme,并且没有找到默认认证和自定义授权的DefaultChallengeScheme [英] No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

查看:67
本文介绍了没有指定authenticationScheme,并且没有找到默认认证和自定义授权的DefaultChallengeScheme的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .NET Core 2.0 应用程序,但有授权问题.我想对特殊请求使用自定义授权.标头和标准默认身份验证.首先,我在Startup.cs中添加配置:

public IServiceProvider ConfigureServices(IServiceCollection services){//...services.AddAuthorization(options =>{options.AddPolicy(DefaultAuthorizedPolicy, policy =>{policy.Requirements.Add(new TokenAuthRequirement());});});services.AddSingleton();//...}

AuthTokenPolicy.cs:

public class AuthTokenPolicy : AuthorizationHandler{受保护的覆盖任务 HandleRequirementAsync(AuthorizationHandlerContext 上下文,TokenAuthRequirement 要求){var filterContext = context.Resource as AuthorizationFilterContext;var response = filterContext.HttpContext.Response;尝试{//一些验证码var isValidToken = isValidTokenTask.Result;如果 (!isValidToken){response.StatusCode = 401;返回 Task.CompletedTask;}response.StatusCode = 200;上下文.成功(要求);}捕获(异常){返回 Task.CompletedTask;}返回 Task.CompletedTask;}}

HomeController.cs中:

[Authorize(Policy = Startup.DefaultAuthorizedPolicy)]公共异步任务可见()

如果我在 AuthTokenPolicy 中使用了错误的 request.header,我会看到它,但在日志中我会看到这个错误:

<块引用>

System.InvalidOperationException: 未指定 authenticationScheme,也未找到 DefaultChallengeScheme. 在 Microsoft.AspNetCore.Authentication.AuthenticationService.d__11.MoveNext() --- 上一个堆栈跟踪结束抛出异常的位置 --- 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 Microsoft.AspNetCore.Mvc.ChallengeResult.d__14.MoveNext() --- 从上一个抛出异常的位置的堆栈跟踪结束--- 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__19.MoveNext() --- 从上一个位置开始的堆栈跟踪结束异常被抛出 --- 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__17.MoveNext() ---从上一个抛出异常的位置结束堆栈跟踪 --- 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__15.MoveNext() --- 从上一个抛出异常的位置的堆栈跟踪结束--- 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext() --- 结束来自先前抛出异常的位置的堆栈跟踪 --- 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.d__3.MoveNext() --- 堆栈跟踪结束从之前抛出异常的位置 --- 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 React.AspNet.BabelFileMiddleware.d__5.MoveNext() --- 从上一个抛出异常的位置的堆栈跟踪结束--- 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.d__6.MoveNext() --- 来自上一个异常位置的堆栈跟踪结束抛出 --- 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 core.common.Middleware.LoggingMiddleware.d__3.MoveNext() 在 D:DevmicroservicePDPTemplatecore.commonMiddlewareLoggingMiddleware.cs:line 72

阅读迁移身份验证和身份后到 ASP.NET Core 2.0 我在 startup.cs 中添加了这段代码

文章引用:

services.AddAuthentication(options =>{options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;});

<块引用>

如果满足以下条件之一,则在 2.0 中定义默认方案:您希望用户自动登录您使用 [Authorize] 属性或授权策略而不指定方案

我在 ConfigureServices() 中添加了 AuthenticationSchemeDefaultChallengeScheme.它没有帮助,这里是同样的错误.我尝试在 Startup.Configure() 方法中使用 app.UseAuthentication(); ,但没有结果.

如何在没有身份验证的情况下使用自定义授权?

解决方案

不要使用授权代替身份验证.我应该完全有权使用标题为所有客户提供服务.

工作代码是:

public class TokenAuthenticationHandler : AuthenticationHandler{公共 IServiceProvider ServiceProvider { 获取;放;}公共 TokenAuthenticationHandler(IOptionsMonitor 选项、ILoggerFactory 记录器、UrlEncoder 编码器、ISystemClock 时钟、IServiceProvider serviceProvider):基础(选项、记录器、编码器、时钟){服务提供者 = 服务提供者;}protected override TaskHandleAuthenticateAsync(){var headers = Request.Headers;var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);if (string.IsNullOrEmpty (token)) {return Task.FromResult (AuthenticateResult.Fail (Token is null"));}bool isValidToken = false;//在这里检查令牌如果(!isValidToken){return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));}var claim = new [] { new Claim (token", token) };var identity = new ClaimsIdentity(claims, nameof(TokenAuthenticationHandler));var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);return Task.FromResult (AuthenticateResult.Success (ticket));}}

Startup.cs:

#region 认证services.AddAuthentication (o => {o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;}).AddScheme(SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });#endregion

还有 mycontroller.cs:

[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]公共类 MainController : BaseController{ ... }

我现在找不到 TokenAuthenticationOptions,但它是空的.我找到了同一个类 PhoneNumberAuthenticationOptions:

 public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions{公共正则表达式 PhoneMask { 获取;放;}//= new Regex("7\d{10}");}

您应该定义静态类SchemesNamesConst.类似的东西:

公共静态类 SchemesNamesConst{public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";}

I have a .NET Core 2.0 app and have a problem with authorization. I want to use custom authorization with special requests. Header and standard default authentication. First, I add configuration in Startup.cs:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddAuthorization(options =>
    {
        options.AddPolicy(DefaultAuthorizedPolicy, policy =>
        {
            policy.Requirements.Add(new TokenAuthRequirement());
        });
    });
    services.AddSingleton<IAuthorizationHandler, AuthTokenPolicy>();
    // ...
}

AuthTokenPolicy.cs:

public class AuthTokenPolicy : AuthorizationHandler<TokenAuthRequirement>
{   
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TokenAuthRequirement requirement)
    {
        var filterContext = context.Resource as AuthorizationFilterContext;
        var response = filterContext.HttpContext.Response;
        try
        {
            // some validation code

            var isValidToken = isValidTokenTask.Result;
            if (!isValidToken)
            {
                response.StatusCode = 401;
                return Task.CompletedTask;
            }

            response.StatusCode = 200;
            context.Succeed(requirement);
        }
        catch (Exception)
        {
            return Task.CompletedTask;
        }
        return Task.CompletedTask;
    }
}

and in HomeController.cs:

[Authorize(Policy = Startup.DefaultAuthorizedPolicy)]
public async Task<IActionResult> IsVisible()

If I use the wrong request.header in AuthTokenPolicy I see it, but in the logs I see this error:

System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. at Microsoft.AspNetCore.Authentication.AuthenticationService.d__11.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Mvc.ChallengeResult.d__14.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__19.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__17.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__15.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.d__3.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at React.AspNet.BabelFileMiddleware.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at core.common.Middleware.LoggingMiddleware.d__3.MoveNext() in D:DevmicroservicePDPTemplatecore.commonMiddlewareLoggingMiddleware.cs:line 72

After reading Migrating Authentication and Identity to ASP.NET Core 2.0 I've added this code in startup.cs

Quotation from the article :

services.AddAuthentication(options => 
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
});

Define a default scheme in 2.0 if one of the following conditions is true: You want the user to be automatically signed in You use the [Authorize] attribute or authorization policies without specifying schemes

I added AuthenticationScheme and DefaultChallengeScheme in ConfigureServices(). It didn't help, the same error here. I've tried to use app.UseAuthentication(); in the Startup.Configure() method, with no results.

How can I use a custom authorization without authentication?

解决方案

Do not use authorization instead of authentication. I should get whole access to service all clients with header.

The working code is:

public class TokenAuthenticationHandler : AuthenticationHandler<TokenAuthenticationOptions> 
{
    public IServiceProvider ServiceProvider { get; set; }

    public TokenAuthenticationHandler (IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider) 
        : base (options, logger, encoder, clock) 
    {
        ServiceProvider = serviceProvider;
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync () 
    {
        var headers = Request.Headers;
        var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);

        if (string.IsNullOrEmpty (token)) {
            return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
        }           

        bool isValidToken = false; // check token here

        if (!isValidToken) {
            return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
        }

        var claims = new [] { new Claim ("token", token) };
        var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
        var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
        return Task.FromResult (AuthenticateResult.Success (ticket));
    }
}

Startup.cs:

#region Authentication
services.AddAuthentication (o => {
    o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion

And mycontroller.cs:

[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }

I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions:

public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
{
    public Regex PhoneMask { get; set; }// = new Regex("7\d{10}");
}

You should define static class SchemesNamesConst. Something like:

public static class SchemesNamesConst
{
    public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}

这篇关于没有指定authenticationScheme,并且没有找到默认认证和自定义授权的DefaultChallengeScheme的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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