-
-
Save fcoury/3c3d15a662cf8fd27ce56595de2334ac 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
This file contains hidden or 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
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("~/"); | |
} | |
} | |
} |
This file contains hidden or 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.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; | |
} | |
} | |
} |
This file contains hidden or 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
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