User authentication asp.net core web api

I want to use the secret key (api key) authorization asp.net core web api. The key will be passed in the authorization header, as indicated below,

ex. Authorization keytype;h43484344343bbhfdjfdfhj34343

I want to write middleware to read this key from the request headers and call the internal api to verify the key.

In the web api, we can write a message handler to do this, but I'm new to the asp.net core. I see a lot of samples, but they use JWT token authentication built in. But I wanted to use my own key, and I decrypt this key and check it for writing to the database.

Can someone suggest some code examples on how to do this?

+4
source share
1 answer

, asp core 1.1. :

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

AuthenticationHandler<TOptions>. :

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 -property :

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 ...
}

, , , !

+6
source

Source: https://habr.com/ru/post/1686848/


All Articles