Code Monkey home page Code Monkey logo

znetcs.aspnetcore.authentication.basic's Introduction

ZNetCS.AspNetCore.Authentication.Basic

NuGet Build

A simple basic authentication middleware. Allows setup authentication using configuration or dependency injection and suppress WWW-Authenticate header globally or for AJAX request.

Installing

Install using the ZNetCS.AspNetCore.Authentication.Basic NuGet package

PM> Install-Package ZNetCS.AspNetCore.Authentication.Basic

Version history

6.0.0

Cleanup events initialization and nullable checkup. Events are now only initialized in handler not in options. Unless configured during initialization (no change in code is required, it is just code cleanup). Logger improvements.

5.0.0

Added direct references to latest framework and removed no longer supported frameworks. Added possibility to suppress WWWAuthenticate header globally not only on Ajax request.

4.0.0

From now assembly is signed.

3.0.0

The OnValidatePrincipal will not return AuthenticationResult any more. To simplify process can simply return Task.CompletedTask. Also to make success authentication Principal have to be assigned to ValidatePrincipalContext context.

Usage

When you install the package, it should be added to your .csproj. Alternatively, you can add it directly by adding:

<ItemGroup>
    <PackageReference Include="ZNetCS.AspNetCore.Authentication.Basic" Version="6.0.1" />
</ItemGroup>
using ZNetCS.AspNetCore.Authentication.Basic;
using ZNetCS.AspNetCore.Authentication.Basic.Events;
...

.NET 6

In order to use the basic authentication middleware, you must configure the services in the Program.cs file.

// Add services to the container.
builder.Services
    .AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
    .AddBasicAuthentication(
        options =>
        {
            options.Realm = "My Application";
            options.Events = new BasicAuthenticationEvents
            {
                OnValidatePrincipal = context =>
                {
                    if ((context.UserName == "userName") && (context.Password == "password"))
                    {
                        var claims = new List<Claim>
                        {
                            new Claim(ClaimTypes.Name, context.UserName, context.Options.ClaimsIssuer)
                        };

                        var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
                        context.Principal = principal;
                    }
                    else 
                    {
                        // optional with following default.
                        // context.AuthenticationFailMessage = "Authentication failed."; 
                    }

                    return Task.CompletedTask;
                }
            };
        });

or using dependency injection

public class AuthenticationEvents : BasicAuthenticationEvents
{
    #region Public Methods

    /// <inheritdoc/>
    public override Task ValidatePrincipalAsync(ValidatePrincipalContext context)
    {
        if ((context.UserName == "userName") && (context.Password == "password"))
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, context.UserName, context.Options.ClaimsIssuer)
            };

            var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
            context.Principal = principal;
        }

        return Task.CompletedTask;
    }

    #endregion
}

and then registration

builder.Services.AddScoped<AuthenticationEvents>();

builder.Services
    .AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
    .AddBasicAuthentication(
        options =>
        {
            options.Realm = "My Application";
            options.EventsType = typeof(AuthenticationEvents);
        });

then

// configure default authentication initialization
app.UseAuthentication();

// other middleware e.g. MVC etc

.NET 5 and Below

In order to use the basic authentication middleware, you must configure the services in the Configure and ConfigureServices call of Startup. Because basic authentication is manual process handled on each request, there is need to validate credentials manually (see below).

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{   

    // default authentication initialization
    app.UseAuthentication();

    // other middleware e.g. MVC etc
}

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
        .AddBasicAuthentication(
            options =>
            {
                options.Realm = "My Application";
                options.Events = new BasicAuthenticationEvents
                {
                    OnValidatePrincipal = context =>
                    {
                        if ((context.UserName == "userName") && (context.Password == "password"))
                        {
                            var claims = new List<Claim>
                            {
                                new Claim(ClaimTypes.Name, context.UserName, context.Options.ClaimsIssuer)
                            };

                            var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
                            context.Principal = principal;
                        }
                        else 
                        {
                            // optional with following default.
                            // context.AuthenticationFailMessage = "Authentication failed."; 
                        }

                        return Task.CompletedTask;
                    }
                };
            });
}

or using dependency injection:

public class AuthenticationEvents : BasicAuthenticationEvents
{
    #region Public Methods

    /// <inheritdoc/>
    public override Task ValidatePrincipalAsync(ValidatePrincipalContext context)
    {
        if ((context.UserName == "userName") && (context.Password == "password"))
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, context.UserName, context.Options.ClaimsIssuer)
            };

            var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
            context.Principal = principal;
        }

        return Task.CompletedTask;
    }

    #endregion
}

and then registration

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<AuthenticationEvents>();

    services
        .AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
        .AddBasicAuthentication(
            options =>
            {
                options.Realm = "My Application";
                options.EventsType = typeof(AuthenticationEvents);
            });
}

As from version 3.0.1 You can suppress the response WWW-Authenticate header (avoiding the browser to show a popup) for ajax requests by using a switch.

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<AuthenticationEvents>();

    services
        .AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
        .AddBasicAuthentication(
            options =>
            {
                options.Realm = "My Application";
                options.AjaxRequestOptions.SuppressWwwAuthenticateHeader = true;
            });
}

znetcs.aspnetcore.authentication.basic's People

Contributors

msmolka avatar vborioni-onit avatar md2perpe avatar jeldert avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.