Skip to content

Instantly share code, notes, and snippets.

@woodss
Last active August 29, 2015 14:10
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 woodss/8ceece7b152a87eabba4 to your computer and use it in GitHub Desktop.
Save woodss/8ceece7b152a87eabba4 to your computer and use it in GitHub Desktop.
Custom Authentication Attributes in ASP.NET MVC
namespace YourProject.Models
{
public class RequiresAuthenticationAttribute: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string LoginPath = "/Login"; // Path to your login page
// Check authentication
Authentication auth = new Authentication();
// ^ Your Custom authentication class
if (!auth.isAuthenticated()) /* <<< Your authentication condition */
{
// Not authenticated
// Need to login, redirect away from the
// controller action!
Debug.Print("Authentication REQUIRED!");
filterContext.Result = new RedirectResult(LoginPath);
}
else
{
// Authenticated
// If we get here, the attribute will end, and
// defer execution back to the controller action
// from which it was invoked.
Debug.Print("User is authenticated");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment