Skip to content

Instantly share code, notes, and snippets.

@jchannon
Last active March 29, 2017 12:40
Show Gist options
  • Save jchannon/c6e6de3e67c85bc181b8078dc8af9ccb to your computer and use it in GitHub Desktop.
Save jchannon/c6e6de3e67c85bc181b8078dc8af9ccb to your computer and use it in GitHub Desktop.
How to use ASP.Net Core Cookie Middleware and sign the user in within a Nancy module
public class AuthModule : NancyModule
{
public AuthModule()
{
Post("/login", async _ =>
{
var myclaims = new List<Claim>(new Claim[] { new Claim("Id", "SOME USER ID FROM SOMEWHERE!!") });
var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(myclaims, "MyCookieMW"));
await this.Context.GetAuthenticationManager()
.SignInAsync("MyCookieMW", claimsPrincipal,
new AuthenticationProperties()
{
AllowRefresh = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(20),
IsPersistent = false
});
return Response.AsRedirect("~/");
}
}
}
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http.Authentication;
using Nancy;
namespace MyApp
{
public static class NancyContextExtensions
{
public static AuthenticationManager GetAuthenticationManager(this NancyContext context, bool throwOnNull = false)
{
object requestEnvironment;
context.Items.TryGetValue(Nancy.Owin.NancyMiddleware.RequestEnvironmentKey, out requestEnvironment);
var environment = requestEnvironment as IDictionary<string, object>;
if (environment == null && throwOnNull)
{
throw new InvalidOperationException("OWIN environment not found. Is this an owin application?");
}
return environment != null ? ((Microsoft.AspNetCore.Http.DefaultHttpContext)environment["Microsoft.AspNetCore.Http.DefaultHttpContext"]).Authentication : null;
}
}
}
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AutomaticAuthenticate = true,
CookieSecure = CookieSecurePolicy.SameAsRequest,
AuthenticationScheme = "MyCookieMW",
CookieHttpOnly = true,
SlidingExpiration = true,
CookieName = "MyCookie",
});
app.UseOwin(x => x.UseNancy());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment