I'm building my own membership system and I want nothing to do with the MS Membership provider. I've looked around the internet and here on StackOverflow but all I could found was membership providers built on top of the MS Membership provider.
Anyway, I've got almost everything hooked up now, but I'd like to use a custom Authorize attribute which utilized my membership infrastructure. I checked out this thread here on the site and I'm trying to do something similar, but I'm not sure that's quiet what I need. So far these are the classes I've got:
SessionManager:
public static class SessionManager : ISessionManager
{
public static void RegisterSession(string key, object obj)
{
System.Web.HttpContext.Current.Session[key] = obj;
}
public static void FreeSession(string key)
{
System.Web.HttpContext.Current.Session[key] = null;
}
public static bool CheckSession(string key)
{
if (System.Web.HttpContext.Current.Session[key] != null)
return true;
else
return false;
}
public static object ReturnSessionObject(string key)
{
if (CheckSession(key))
return System.Web.HttpContext.Current.Session[key];
else
return null;
}
}
SharweAuthorizeAttribute: (I am not really sure if that's actually what I should be doing)
public class SharweAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (SessionManager.CheckSession(SessionKeys.User) == true)
return true;
else
return false;
}
}
Now here's what I need:
- Is my SharweAuthorizeAttribute class correct in the first place?
- I need to be able to redirect unauthenticated users to the login page
I need to authorize users based on their roles (using my own role provider) so I would do something like:
[SharweAuthorize(Roles="MyRole")]
That's it I guess... Any suggestions are more than welcome :)
UPDATE: Ok I just read that page again and found the solution to question number two:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (SessionManager.CheckSession(SessionKeys.User) == false)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "ActionName" },
{ "controller", "ControllerName" }
});
}
else
base.HandleUnauthorizedRequest(filterContext);
}
Let me know if I got it right please...
See Question&Answers more detail:os