Skip to content

Instantly share code, notes, and snippets.

@programatt
Last active March 29, 2017 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save programatt/b704c6e4c3b33c7640b9d0302efa23b1 to your computer and use it in GitHub Desktop.
Save programatt/b704c6e4c3b33c7640b9d0302efa23b1 to your computer and use it in GitHub Desktop.
inline middleware that does the auth process
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Net;
public static class BuilderExtensions
{
public static IApplicationBuilder UseSillyAuthentication(this IApplicationBuilder app,Func<HttpContext,bool> authorizeFunc)
{
app.Use(async (context, next) =>
{
//Do work to figure out if authorized request
var authorized = authorizeFunc(context);
if (authorized)
{
await next();
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.WriteAsync("Today is not the day to call this api");
}
});
return app;
}
}
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseSillyAuthentication(AuthorizeRequest);
app.Run(async (context) =>
{
await context.Response.WriteAsync("Lucky day!!!");
});
}
private bool AuthorizeRequest(HttpContext context)
{
//Only authorize requests when the day of the week is even
//because reasons
return (int)DateTime.Now.DayOfWeek % 2 == 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment