Last active
August 19, 2020 13:47
-
-
Save rstropek/5223cfe72be7fa190cb36b7d792e04a5 to your computer and use it in GitHub Desktop.
Use case for C# 9's attributes on local functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Security.Claims; | |
using System.Text.Encodings.Web; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Authentication; | |
using Microsoft.AspNetCore.Authorization; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Hosting; | |
using Microsoft.Extensions.Logging; | |
using Microsoft.Extensions.Options; | |
Host.CreateDefaultBuilder(args) | |
.ConfigureWebHostDefaults(webBuilder => | |
{ | |
webBuilder.ConfigureServices(services => | |
{ | |
services | |
.AddAuthentication("MyScheme") | |
.AddScheme<DummyAuthenticationOptions, DummyAuthenticationHandler>("MyScheme", options => { }); | |
services.AddAuthorization(); | |
}) | |
.Configure(app => | |
{ | |
app.UseRouting(); | |
app.UseAuthentication(); | |
app.UseAuthorization(); | |
app.UseEndpoints(endpoints => | |
{ | |
static async Task SayHello(HttpContext context) => await context.Response.WriteAsync("Public view"); | |
endpoints.MapGet("/", SayHello); | |
[Authorize(AuthenticationSchemes = "MyScheme", Roles = "Admin")] | |
static async Task AdminsOnly(HttpContext context) => await context.Response.WriteAsync("Admin view"); | |
endpoints.MapGet("/secret", AdminsOnly); | |
}); | |
}); | |
}) | |
.Build().Run(); | |
public class DummyAuthenticationOptions : AuthenticationSchemeOptions { } | |
internal class DummyAuthenticationHandler : AuthenticationHandler<DummyAuthenticationOptions> | |
{ | |
public DummyAuthenticationHandler(IOptionsMonitor<DummyAuthenticationOptions> options, | |
ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) | |
: base(options, logger, encoder, clock) { } | |
protected override Task<AuthenticateResult> HandleAuthenticateAsync() | |
{ | |
var claims = new[] | |
{ | |
new Claim(ClaimTypes.NameIdentifier, "Rainer"), | |
new Claim(ClaimTypes.Role, "Admin") | |
}; | |
var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme.Name)); | |
var ticket = new AuthenticationTicket(claimsPrincipal, | |
new AuthenticationProperties { IsPersistent = false }, Scheme.Name); | |
return Task.FromResult(AuthenticateResult.Success(ticket)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment