asp.net-web-api - 自定义身份验证asp.net core web api

标签 asp.net-web-api asp.net-core-webapi custom-authentication

我想使用 key (api key )授权asp.net core web api。 key 将在授权 header 中传递,如下所示,

ex. Authorization keytype;h43484344343bbhfdjfdfhj34343

我想编写一个中间件来从请求 header 中读取此 key 并调用内部 api 来验证该 key 。

在 Web api 中,我们可以编写一个消息处理程序来执行此操作,但我是 ASP.NET Core 的新手。我看到很多示例,但它们使用内置的 JWT token 身份验证。但我想使用自己的 key ,并且解密该 key 并根据数据库条目进行验证。

任何人都可以建议一些关于如何执行此操作的代码示例吗?

最佳答案

我在使用 asp core 1.1 的解决方案中使用了这种方法。首先定义一个自定义方案:

public static class Authentication
{
    public const string Scheme = "Custom";
}

然后你必须继承AuthenticationHandler<TOptions> 。这是验证 header 值的逻辑所在的位置:

public class MyAuthenticationHandler : AuthenticationHandler<MyOptions>
{
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var authorizationHeader = Context.Request.Headers["Authorization"];
        if (!authorizationHeader.Any())
            return Task.FromResult(AuthenticateResult.Skip());

        var value = authorizationHeader.ToString();
        if (string.IsNullOrWhiteSpace(value))
            return Task.FromResult(AuthenticateResult.Skip());

        // place logic here to validate the header value (decrypt, call db etc)

        var claims = new[]
        {
            new Claim(System.Security.Claims.ClaimTypes.Name, "Bob")
        };

        // create a new claims identity and return an AuthenticationTicket 
        // with the correct scheme
        var claimsIdentity = new ClaimsIdentity(claims, Authentication.Scheme);

        var ticket = new AuthenticationTicket(new ClaimsPrincipal(claimsIdentity), new AuthenticationProperties(), Authentication.Scheme);

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

为了继承AuthenticationHandler您必须创建一个选项类,在其中设置 AuthenticationScheme -您正在使用的方案的属性:

public class MyOptions : AuthenticationOptions
{
    AuthenticationScheme = Authentication.Scheme;
}

在此之后你必须继承 AuthenticationMiddleware<TOptions> 。这将创建您在上一步中实现的处理程序:

public class MyAuthenticationMiddleware : AuthenticationMiddleware<MyOptions>
{
    public MyAuthenticationMiddleware(RequestDelegate next, IOptions<MyOptions> options, ILoggerFactory loggerFactory, UrlEncoder encoder) : base(next, options, loggerFactory, encoder)
    {
    }

    protected override AuthenticationHandler<MyOptions> CreateHandler()
    {
        return new MyAuthenticationHandler();
    }
}

为了轻松插入中间件,您可以定义这些扩展方法:

public static IApplicationBuilder UseMyAuthentication(this IApplicationBuilder app, IConfigurationSection config)
{
    return app.UseMyAuthentication(options => {});
}

private static IApplicationBuilder UseMyAuthentication(this IApplicationBuilder app, Action<MyOptions> configure)
{
    var options = new MyOptions();
    configure?.Invoke(options);

    return app.UseMiddleware<MyAuthenticationMiddleware>(new OptionsWrapper<MyOptions>(options));
}

然后在你的Startup中类你终于可以添加你的中间件了:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMyAuthentication(Configuration.GetSection("MyAuthenticationOptions"));

    // other stuff

    app.UseMvc();
}

然后添加AuthorizeAttribute在指定您刚刚创建的方案的操作中:

[Authorize(ActiveAuthenticationSchemes = Authentication.Scheme)]
public IActionResult Get()
{
    // stuff ...
}

有很多步骤,但希望这能帮助您前进!

关于asp.net-web-api - 自定义身份验证asp.net core web api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46556225/

相关文章:

security - Web-api 安全 : SSL?

c# - 让 WebAPI Controller 向另一个 REST 服务发送 http 请求

c# - IFormFile 在 asp.net core 2.1 中总是返回 null

c# - 如何在 asp.net mvc 身份上设置自定义身份验证?

c# - 使用单个模型属性将多个数组值传递给 Web API Controller

asp.net-mvc - 在 ASP.NET Core 中发现通用 Controller

c# - 在 Asp.Net MVC Web Api 中测试 Controller 时,ModelState.IsValid 始终为真

c# - FromBody 收到的帖子导致可序列化错误

django 自定义用户模型组和权限

java - Spring - 从 Controller 调用 custom-authentication-provider