Last active
March 29, 2017 13:09
-
-
Save programatt/b704c6e4c3b33c7640b9d0302efa23b1 to your computer and use it in GitHub Desktop.
inline middleware that does the auth process
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 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