Skip to content

Instantly share code, notes, and snippets.

@corruptmem
Created May 10, 2017 15:07
Show Gist options
  • Save corruptmem/9b88e4a9c658e9d6243dcc6aa6fa8231 to your computer and use it in GitHub Desktop.
Save corruptmem/9b88e4a9c658e9d6243dcc6aa6fa8231 to your computer and use it in GitHub Desktop.
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.2" />
</ItemGroup>
</Project>
using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace CookieExample
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
using System;
using System.Security.Claims;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authentication.Cookies;
namespace CookieExample
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.UseDeveloperExceptionPage();
app.Use(async (ctx, next) =>
{
if (ctx.Request.Path == "/favicon.ico")
{
ctx.Response.StatusCode = 404;
return;
}
await next.Invoke();
});
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
LoginPath = new PathString("/login"),
LogoutPath = new PathString("/logout"),
ExpireTimeSpan = TimeSpan.FromMinutes(1),
SlidingExpiration = true
});
app.Run(async context =>
{
if (context.Request.Path == "/login")
{
var identity = new ClaimsIdentity(new Claim[0], CookieAuthenticationDefaults.AuthenticationScheme);
await context.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
await context.Response.WriteAsync("Signed in");
return;
}
var status = "authenticated? " + context.User.Identity.IsAuthenticated;
if (context.Request.Path == "/exception")
{
throw new Exception(status);
}
await context.Response.WriteAsync(status);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment