Asp.net core ASP.NET Core 3.1的自定义身份验证处理程序授权失败?

Asp.net core ASP.NET Core 3.1的自定义身份验证处理程序授权失败?,asp.net-core,authentication,.net-core-3.1,Asp.net Core,Authentication,.net Core 3.1,我正在尝试实现一个简单的基于api密钥的身份验证处理程序。我的处理程序方法是 protected override Task<AuthenticateResult> HandleAuthenticateAsync() { // Get the apiKey from a store... if (apiKey != header.Parameter) { var error = "Invalid username or api key

我正在尝试实现一个简单的基于api密钥的身份验证处理程序。我的处理程序方法是

protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
    // Get the apiKey from a store...
    if (apiKey != header.Parameter)
    {
        var error = "Invalid username or api key.";
        return Task.FromResult(AuthenticateResult.Fail(error));
    }

    var claims = new List<Claim> {new Claim("user", (string)username)};
    var identity = new ClaimsIdentity(claims);
    var principal = new ClaimsPrincipal(identity);
    var ticket = new AuthenticationTicket(principal, header.Scheme);

    return Task.FromResult(AuthenticateResult.Success(ticket));
}

既然身份验证已经成功了,我如何避免这个挑战?

我认为如果没有更多的代码,可能会有点难以确定问题。我创建了一个示例,它应该能够根据您的需求工作。看看下面的例子

编辑: 如果不想手动配置以下设置,可以查看以下库:

处理者

using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;

namespace WebApplication1.Handlers
{

    public class ApiKeyAuthenticationSchemeOptions
      : AuthenticationSchemeOptions
    { }

    public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationSchemeOptions>
    {
        //TODO Change to whatever name you want to use
        private const string ApiKeyHeaderName = "X-Token";

        public ApiKeyAuthenticationHandler(
           IOptionsMonitor<ApiKeyAuthenticationSchemeOptions> options,
           ILoggerFactory logger,
           UrlEncoder encoder,
           ISystemClock clock)
           : base(options, logger, encoder, clock)
        {
        }

        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.ContainsKey(ApiKeyHeaderName))
            {
                return Task.FromResult(AuthenticateResult.Fail("Header was not found"));
            }

            string token = Request.Headers[ApiKeyHeaderName].ToString();

            //TODO Replace with proper token handling code
            if (token == "secret")
            {
                Claim[] claims = new[] {
                    new Claim(ClaimTypes.NameIdentifier, "john123"),
                    new Claim(ClaimTypes.Email, "john@gmail.com"),
                };

                ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, nameof(ApiKeyAuthenticationHandler));
                AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(claimsIdentity), Scheme.Name);

                return Task.FromResult(AuthenticateResult.Success(ticket));
            }
            else
            {
                return Task.FromResult(AuthenticateResult.Fail("Token is invalid"));
            }
        }
    }
}


我设法找到了答案。基本上,我需要像这样覆盖startup类中的默认授权策略

services.AddAuthorization(o =>
{
    var builder = new AuthorizationPolicyBuilder("ApiKey);
    builder = builder.RequireClaim("user");
    o.DefaultPolicy = builder.Build();
});

我是否需要指定身份验证方案?不管怎么说,没有这个你就可以做吗?不,你不必。您可以将“ApiKey”设置为默认身份验证方案-这在AddAuthentication()方法中发生。但是,请记住通过调用app.UseAuthentication()(在app.UseAuthentication()之前)添加适当的中间件。我更新了上面的示例。
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebApplication1.Handlers;

namespace WebApplication1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication("ApiKey").AddScheme<ApiKeyAuthenticationSchemeOptions, ApiKeyAuthenticationHandler>("ApiKey", op => { });
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace WebApplication1.Controllers
{
    [Route("api/students")]
    [ApiController]
    public class StudentsController : ControllerBase
    {

        [HttpGet("secret")]
        [Authorize]
        public IActionResult GetData()
        {
            string email = User.Claims.ElementAt(1).Value;
            return Ok("Secret data");
        }

        [HttpGet("public")]
        public IActionResult GetData2()
        {
            return Ok("Public data");
        }

    }
}

services.AddAuthorization(o =>
{
    var builder = new AuthorizationPolicyBuilder("ApiKey);
    builder = builder.RequireClaim("user");
    o.DefaultPolicy = builder.Build();
});