Skip to content

Instantly share code, notes, and snippets.

@Saladressing
Created March 29, 2019 00:41
Show Gist options
  • Save Saladressing/50b01dbacd5240117daf834d38783c34 to your computer and use it in GitHub Desktop.
Save Saladressing/50b01dbacd5240117daf834d38783c34 to your computer and use it in GitHub Desktop.
SampleAnonymousSessionMiddleware
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
public class AnonymousSessionMiddleware
{
private readonly RequestDelegate _next;
public AnonymousSessionMiddleware(RequestDelegate next)
{
_next = next;
}
public async System.Threading.Tasks.Task InvokeAsync(HttpContext context)
{
if (!context.User.Identity.IsAuthenticated)
{
if (string.IsNullOrEmpty(context.User.FindFirstValue(ClaimTypes.Anonymous)))
{
var claim = new Claim(ClaimTypes.Anonymous, System.Guid.NewGuid().ToString());
context.User.AddIdentity(new ClaimsIdentity(new[] { claim }));
string scheme = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;
await context.SignInAsync(scheme, context.User, new AuthenticationProperties { IsPersistent = false });
}
}
await _next(context);
}
}
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
string scheme = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;
services.AddAuthentication(scheme)
.AddCookie(scheme);
services.AddMvc()
.AddNewtonsoftJson();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting(routes =>
{
routes.MapControllers();
});
app.UseAuthorization();
app.UseAuthentication();
app.UseMiddleware<AnonymousSessionMiddleware>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment