Last active
August 29, 2015 14:10
-
-
Save woodss/8ceece7b152a87eabba4 to your computer and use it in GitHub Desktop.
Custom Authentication Attributes in ASP.NET MVC
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
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