dotnet core custom authorization for demos
Some times we need small app with auth, for us to not bother with storage, and or full blown frameworks, we may want to use such custom AuthenticationHandler which will take user query string param, and if it is passed, authorize request
Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
public class Program
{
public static void Main(string[] args) => WebHost
.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build()
.Run();
}
// https://joonasw.net/view/creating-auth-scheme-in-aspnet-core-2
public class DemoAuthenticationOptions : AuthenticationSchemeOptions
{
public const string DefaultScheme = "Demo";
}
public class DemoAuthenticationHandler : AuthenticationHandler<DemoAuthenticationOptions>
{
public DemoAuthenticationHandler(IOptionsMonitor<DemoAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Query.ContainsKey("user") || string.IsNullOrEmpty(Request.Query["user"]))
{
return Task.FromResult(AuthenticateResult.NoResult());
}
var claims = new[] { new Claim(ClaimTypes.Name, Request.Query["user"]) };
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
public static class DemoAuthenticationExtensions
{
public static AuthenticationBuilder AddDemoAuthentication(this AuthenticationBuilder build)
{
return build.AddScheme<DemoAuthenticationOptions, DemoAuthenticationHandler>(DemoAuthenticationOptions.DefaultScheme, _ => { });
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = DemoAuthenticationOptions.DefaultScheme;
options.DefaultChallengeScheme = DemoAuthenticationOptions.DefaultScheme;
}).AddDemoAuthentication();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}
}
public class DemoController : ControllerBase
{
// curl -si http://localhost:5000/whoami?user=mac # 200 OK "mac"
// curl -si http://localhost:5000/whoami # 204 No Content
[HttpGet]
[Route(nameof(WhoAmI))]
public string WhoAmI() => User.Identity.Name;
// curl -si http://localhost:5000/secret?user=mac # 200 OK "Secret"
// curl -si http://localhost:5000/whoami # 401 Unauthorized
[Authorize]
[HttpGet]
[Route(nameof(Secret))]
public string Secret() => nameof(Secret);
}