Created
May 10, 2017 15:07
-
-
Save corruptmem/9b88e4a9c658e9d6243dcc6aa6fa8231 to your computer and use it in GitHub Desktop.
This file contains 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.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(); | |
} | |
} | |
} |
This file contains 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; | |
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