没有指定authenticationScheme,也没有找到具有默认身份验证和自定义授权的DefaultChallengeScheme [英] No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization
问题描述
我有一个.NET Core 2.0应用程序,并且授权有问题。我想对特殊请求使用自定义授权。标头和标准默认身份验证。
首先,我在 Startup.cs
中添加配置:
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;
}
}
和 HomeController.cs中
:
[Authorize(Policy = Startup.DefaultAuthorizedPolicy)]
public async Task<IActionResult> IsVisible()
如果我在 AuthTokenPolicy中使用了错误的request.header
我看到了,但是在日志中看到此错误:
If I use the wrong request.header in AuthTokenPolicy
I see it, but in the logs I see this error:
System.InvalidOperationException:未指定authenticationScheme,并且在Microsoft.AspNetCore.Authentication.AuthenticationService.d__11.MoveNext()中没有找到DefaultChallengeScheme。-从上一个引发异常的位置开始的堆栈跟踪--- \在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()中,在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中,在Microsoft.AspNetCore.Mvc中。 ChallengeResult.d__14.MoveNext()\r\n ---从上一个引发异常的位置开始的堆栈跟踪--- \System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)处在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__19.MoveNext()处-从上次引发异常的位置开始的堆栈跟踪-在System.Runtime处。 ExceptionServices.ExceptionDispatchInfo.Throw()—在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__17.MoveNext() \r-n--从上一个引发异常的位置开始的堆栈结束跟踪---在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()处在System.Runtime Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__15.MoveNext()中的.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)\r\n--从上一个异常发生的位置开始的堆栈跟踪在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()被抛出---在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotificatio Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()中的(任务任务)-从上一个引发异常的位置开始的堆栈跟踪-在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()中,在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中,在Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware中, .d__3.MoveNext()\r\n ---从上一个引发异常的位置开始的堆栈跟踪--- SystemSystem.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)处的React.AspNet.BabelFileMiddleware.d__5.MoveNext()处的Rn-从上一个版本开始的堆栈跟踪引发异常的位置--- System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()中的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotifi阳离子(任务任务)在Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.d__6.MoveNext()处执行-从上次引发异常的位置开始的堆栈跟踪--- \在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()中,在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中,在core.common.Middleware.LoggingMiddleware中, D中的.d__3.MoveNext():Dev\microservicePDP\Template\core.common\Middleware\LoggingMiddleware.cs:第72行
System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found.\r\n at Microsoft.AspNetCore.Authentication.AuthenticationService.d__11.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Mvc.ChallengeResult.d__14.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__19.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__17.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__15.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.d__3.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at React.AspNet.BabelFileMiddleware.d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at core.common.Middleware.LoggingMiddleware.d__3.MoveNext() in D:\Dev\microservicePDP\Template\core.common\Middleware\LoggingMiddleware.cs:line 72
阅读将身份验证和身份迁移到ASP.NET Core 2.0 我已将此代码添加到startup.cs中。
After reading Migrating Authentication and Identity to ASP.NET Core 2.0 I've added this code in startup.cs
文章引用:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
});
如果满足以下条件之一,则在2.0中定义默认方案:
您希望用户自动登录
您使用[Authorize]属性或授权策略而未指定方案
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
我在 ConfigureServices()$ c $中添加了
AuthenticationScheme
和 DefaultChallengeScheme
c>。并没有帮助,这里是同样的错误。我试图在 Startup.Configure()
方法中使用 app.UseAuthentication();
,但没有结果。
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?
推荐答案
Okey。正确的答案是:不要使用授权代替身份验证。我应该可以完全访问带有标头的所有客户端。
工作代码为:
Okey. The correct answer is: 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:
Startup.cs :
#region Authentication
services.AddAuthentication (o => {
o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion
和mycontroller.cs
And mycontroller.cs
[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }
我现在找不到TokenAuthenticationOptions,但是它是空的。我发现相同的类PhoneNumberAuthenticationOptions:
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}");
}
您应定义静态类 SchemesNamesConst
。像这样的东西:
You should define static class SchemesNamesConst
. Something like:
public static class SchemesNamesConst
{
public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}
这篇关于没有指定authenticationScheme,也没有找到具有默认身份验证和自定义授权的DefaultChallengeScheme的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!