Reputation: 639
I am trying to make it easier to the developer, Because there are multiple options of Authentication, and not all pages require authentication or full authentication.
In WebForms I can have a generic page, Now each page inherits GenericPage, and only need to implemenet AuthorizationType (see code below)
Can I do anything similiar with Razor? Or maybe I should somthing entirely different...
Here is the code in WebForms:
public class GenericPage : Page
{
public enum AuthorizationType
{
Users = 1,
AuthUsers = 2,
Admins = 4
}
public virtual bool IsAuth()
{
return Authenticator.IsAuth();
}
public virtual bool IsAdmin()
{
AuthUser authUser = Authenticator.GetAuthenticatedUser();
return (authUser != null && authUser.IsAdmin)
}
protected abstract AuthorizationType Authorization
{
get;
}
protected virtual string OnAuthorizationFailedUrl
{
get
{
return HomePageUrl;
}
}
protected void CheckAuthentication()
{
if (!IsUserAuthroized())
Response.Redirect(OnAuthorizationFailedUrl);
}
protected bool IsUserAuthroized()
{
AuthorizationType authorization = Authorization;
return (Authorization.Contains(AuthorizationType.Users) ||
(Authorization.Contains(AuthorizationType.AuthUsers) && IsAuth()) ||
(Authorization.Contains(AuthorizationType.Admins) && IsAdmin()));
}
override OnPageLoad()
{
CheckAuthentication();
}
}
Thanks in advance.
Upvotes: 0
Views: 2490
Reputation: 319
In your scenario, it can be implemented as 3 types of Roles. When you authenticate users, assign the roles correctly.
Then in your controller, or controller action methods, you can put Authorize attribute
[Authorize(Roles = "Users")]
or multiple roles
[Authorize(Roles = "Users,Admins")]
If you want to filter globally, you can create a BaseController and give the Authorize attribute to the controller. Then all of your controllers need to implement the BaseController.
Here is my blog post about how to implement Authentication with customized identity.
Hope this may help you
Upvotes: 3
Reputation: 3481
You can add this type of authorization as a global filter.
http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html
Upvotes: 2