Skip to content

Instantly share code, notes, and snippets.

@iwillspeak iwillspeak/.gitignore Secret
Last active Mar 4, 2019

Embed
What would you like to do?
Http Auth in ASP .NET Core
bin/
obj/
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Authentication;
using test.Authentication;
namespace test.Authentication
{
public static class AuthenticationExtensions
{
public static AuthenticationBuilder AddSimpleTokenAuth(this AuthenticationBuilder builder, Action<TokenAuthOptions> options)
{
return builder.AddScheme<TokenAuthOptions, SimpleTokenAuthHandler>(TokenAuthOptions.DefaultScheme, options);
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace test
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
using System.Security.Principal;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
namespace test.Authentication
{
public class SimpleTokenAuthHandler : AuthenticationHandler<TokenAuthOptions>
{
public SimpleTokenAuthHandler(IOptionsMonitor<TokenAuthOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (Request.Query.ContainsKey("auth"))
{
var identity = new GenericIdentity("test_user", "queryString");
var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), Options.Scheme);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
return Task.FromResult(AuthenticateResult.NoResult());
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace test
{
using System.Text;
using Authentication;
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services
.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = TokenAuthOptions.DefaultScheme;
o.DefaultChallengeScheme = TokenAuthOptions.DefaultScheme;
})
.AddSimpleTokenAuth(o => {});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app
.UseAuthentication()
.Run(async context =>
{
if (context.User?.Identities == null)
{
await context.Response.WriteAsync("No user identities");
}
foreach (var identity in context.User.Identities)
{
var sb = new StringBuilder();
sb.AppendLine("Identity");
sb.AppendLine($" Name: {identity.Name}");
sb.AppendLine($" Label: {identity.Label}");
sb.AppendLine($" AuthType: {identity.AuthenticationType}");
sb.AppendLine($" Authenticated?: {identity.IsAuthenticated}");
var claims = string.Join(", ", identity.Claims.Select(c => c.Value));
sb.AppendLine($" Claims: {claims}");
await context.Response.WriteAsync(sb.ToString());
}
});
}
}
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.3" />
</ItemGroup>
</Project>
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Primitives;
namespace test.Authentication
{
public class TokenAuthOptions : AuthenticationSchemeOptions
{
public const string DefaultScheme = nameof(SimpleTokenAuthHandler);
public string Scheme => DefaultScheme;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.