Skip to content

Instantly share code, notes, and snippets.

@chrisnicola
Created February 19, 2011 20:41
Show Gist options
  • Save chrisnicola/835350 to your computer and use it in GitHub Desktop.
Save chrisnicola/835350 to your computer and use it in GitHub Desktop.
PerWebRequest
public RetailStreamHandler(IDocumentRepository<ShoppingCart> cartRepository)
{
_cartRepository = cartRepository;
Get["/cart"] = x => GetListing();
Post["/cart"] = x => PostNewShoppingCart(Request.Body.FromJson<ShoppingCartForm>());
Get["/cart/{id}"] = x => GetById(x.id);
}
[RequiresAuthentication]
public virtual Response PostNewShippingCart(ShoppingCartForm form)
{
var shoppingCart = new ShoppingCart
{
Id = Guid.NewGuid(),
Products = form.Products,
User = Identity.Name
};
_cartRepository.Create(shoppingCart);
return Response.AsJson(shoppingCart).Created();
}
public class AuthenticationInterceptor : IInterceptor
{
bool CanIntercept(IInvocation invocation) { return invocation.Method.GetCustomAttributes(true).Any(a => a is RequiresAuthenticationAttribute); }
public void Intercept(IInvocation invocation)
{
if (!CanIntercept(invocation)) invocation.Proceed();
else
{
var module = invocation.InvocationTarget as NancyModule;
var authModule = invocation.InvocationTarget as IAuthenticated;
var roles = invocation.Method.GetCustomAttributes(true)
.Cast<RequiresAuthenticationAttribute>().Select(x => x.Role).ToArray();
try
{
if (module.Request.Query.api_key == "Password")
{
if (authModule != null)
authModule.Principal = new MyPrincipal("23C065FA-1E4C-484B-8B80-5FD19863254E", roles);
invocation.Proceed();
}
else
invocation.ReturnValue = new Response {StatusCode = HttpStatusCode.Unauthorized};
}
catch (RuntimeBinderException)
{
invocation.ReturnValue = new Response {StatusCode = HttpStatusCode.Unauthorized};
}
}
}
}
public class AuthenticationFacility : AbstractFacility
{
protected override void Init()
{
Kernel.ComponentRegistered += Kernel_ComponentRegistered;
}
void Kernel_ComponentRegistered(string key, IHandler handler)
{
if (typeof(NancyModule).IsAssignableFrom(handler.ComponentModel.Implementation)
&& typeof(IAuthenticated).IsAssignableFrom(handler.ComponentModel.Implementation))
handler.ComponentModel.Interceptors.Add(InterceptorReference.ForType<AuthenticationInterceptor>());
}
}
public interface IAuthenticated
{
IIdentity Identity { get; }
IPrincipal Principal { get; set; }
}
<system.web>
<compilation debug="true" targetframework="4.0" />
<httpmodules>
<add type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule" name="PerWebRequest" />
</httpmodules>
</system.web>
<system.webserver>
<modules runallmanagedmodulesforallrequests="true">
<add type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule" name="PerWebRequest" />
</modules>
</system.webserver>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment