Razor pages assign roles to users - razor-pages

I am wondering how to create and assign roles in Razor Pages 2.1. application.
I have found how to make them for MVC application (How to create roles in asp.net core and assign them to users and http://hishambinateya.com/role-based-authorization-in-razor-pages), however it does not work for razor pages as I have no IServicesProvider instance.
What I want is just to create admin role and assign it to seeded administrator account. Something similar has been done in this tutorial https://learn.microsoft.com/en-us/aspnet/core/security/authorization/secure-data?view=aspnetcore-2.1, but it seems be sutied for MVC and does not work properly after I applied it to my application. Please help me to understand how to create and seed roles in Razor Pages.
Will be very greatfull for help!

I handle the task next way. First, I used code proposed by Paul Madson in How to create roles in asp.net core and assign them to users. Abovementioned method I have inserted into Startup.cs. It creates administrator role and assigned it to seeded user.
private void CreateRoles(IServiceProvider serviceProvider)
{
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
Task<IdentityResult> roleResult;
string email = "someone#somewhere.com";
//Check that there is an Administrator role and create if not
Task<bool> hasAdminRole = roleManager.RoleExistsAsync("Administrator");
hasAdminRole.Wait();
if (!hasAdminRole.Result)
{
roleResult = roleManager.CreateAsync(new IdentityRole("Administrator"));
roleResult.Wait();
}
//Check if the admin user exists and create it if not
//Add to the Administrator role
Task<ApplicationUser> testUser = userManager.FindByEmailAsync(email);
testUser.Wait();
if (testUser.Result == null)
{
ApplicationUser administrator = new ApplicationUser
{
Email = email,
UserName = email,
Name = email
};
Task<IdentityResult> newUser = userManager.CreateAsync(administrator, "_AStrongP#ssword!123");
newUser.Wait();
if (newUser.Result.Succeeded)
{
Task<IdentityResult> newUserRole = userManager.AddToRoleAsync(administrator, "Administrator");
newUserRole.Wait();
}
}
}
Then, in the same file in Configure method I add argument (IServiceProvider serviceProvider), so you should have something like Configure(..., IServiceProvider serviceProvider). In the end of Configure method I add
CreateRoles(serviceProvider).
To make this code work create ApplicationUser class somwhere, for example in Data folder:
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Sobopedia.Data
{
public class ApplicationUser: IdentityUser
{
public string Name { get; set; }
}
}
Finally, inside ConfigureServices method substitute
services.AddIdentity<ApplicationUser>()
.AddEntityFrameworkStores<SobopediaContext>()
.AddDefaultTokenProviders();
with
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<SobopediaContext>()
.AddDefaultTokenProviders();
As a result, after programm starts in table AspNetRoles you will get a new role, while in table AspNetUsers you will have a new user acuiering administrator role.
Unfortunatelly, after you add the following code
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<SobopediaContext>()
.AddDefaultTokenProviders();
pages Login and Registration stop working. In order to handle this problem you may follow next steps:
Scaffold Identity following (https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.1&tabs=visual-studio).
Then substitute IdentityUser for ApplicationUser in entire solution. Preserv only IdentityUser inheritance in ApplicationUser class.
Remove from Areas/identity/Pages/Account/Register.cs all things related to EmailSernder if you have no its implementation.
In order to check correctness of the roles system you may do as follows. In the end of ConfigureServices method in Startup.cs add this code:
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
});
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizeFolder("/Contact","RequireAdministratorRole");
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
If it does not worki then just add [Authorize(Roles = "Administrator")] to Contact Page model, so it will look something like this:
namespace Sobopedia.Pages
{
[Authorize(Roles = "Administrator")]
public class ContactModel : PageModel
{
public string Message { get; set; }
public void OnGet()
{
Message = "Your contact page.";
}
}
}
Now, in order to open Contact page you should be logged in with login someone#somewhere.com and password _AStrongP#ssword!123.

Related

Servicestack Roles Users and Groups

Since roles don't contain permissions. I am a bit confused by the Roles and Permission in ServiceStack. It appears they are really the same thing? I want to implement a Group, that has roles, that has permissions. Based on the servicestack default implementation I don't think I can extend the provider and get the nested information.
How would i achieve this and still use the authentication attributes.
If i had an attribute
[RequiredPermission("CanAccessPerm")]
That is in Role:HasAccessRole That is in Group:HasAccessGroup
I would want to only use perms to determine access at the API level. Then Roles and Groups to determine who has perms. If Roles contained permissions then I could just extend the CredentialsAuthProvider TryAuthenticate and additionally look at a group table. Is there a way to do this and not rewrite the whole authentication?
Edit 12/12
I am using
container.Register(c =>
new OrmLiteAuthRepository(c.Resolve())
{
UseDistinctRoleTables = AppSettings.Get("UseDistinctRoleTables", true),
});
How do I get to the IManage roles? I see i can override the IAuthRepository.
I found this link. But its not a replacement for Auth
ServiceStack - roles and permissions
-_Edit 12/29 -- It is not calling the methods in MyOrmLiteAuthRepository. Do you know why?
AppHost.cs
container.Register<IAuthRepository>(c =>
new MyOrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())
{
UseDistinctRoleTables = AppSettings.Get("UseDistinctRoleTables", true),
});
CustomAuthRepo
public class MyOrmLiteAuthRepository : OrmLiteAuthRepository
{
public MyOrmLiteAuthRepository(IDbConnectionFactory dbFactory) : base(dbFactory) { }
public MyOrmLiteAuthRepository(IDbConnectionFactory dbFactory, string namedConnnection = null)
: base(dbFactory, namedConnnection)
{
DbFactory = dbFactory;
NamedConnnection = namedConnnection;
}
public IDbConnectionFactory DbFactory { get; set; }
public string NamedConnnection { get; set; }
public override ICollection<string> GetPermissions(string userAuthId)
{
var permissions = base.GetPermissions(userAuthId);
using (var ss = HostContext.ResolveService<SecurityService>(new BasicRequest()))
{
permissions = ss.UserPermissions(Convert.ToInt32(userAuthId));
}
return permissions;
}
public override bool HasPermission(string userAuthId, string permission)
{
var hasPermission = base.HasPermission(userAuthId, permission);
using (var ss = HostContext.ResolveService<SecurityService>(new BasicRequest()))
{
hasPermission = ss.UserHasPermInRoleOrGroup(permission, Convert.ToInt32(userAuthId));
}
return hasPermission;
}
}
Roles/Permissions work similar in that a User can have multiple Roles and Permissions but they're logically different in that a Role defines the Role a person has like "Employee", "Manager", etc and Permission defines functionality they have access to like "CanSubmitPurchaseOrders", "CanRefundCustomers", etc.
ServiceStack doesn't support Roles having permissions themselves but you can implement this functionality yourself in your own Custom AuthProvider by overriding OnAuthenticated() and populating the Permissions collections of AuthUserSession with a combination of all the permissions in all the Roles a User is in. If you're not using a custom AuthProvider you can modify the Users Session by implementing the OnAuthenticated() Session of Auth Event Hooks.
Alternatively if you're using an AuthRepository like OrmLiteAuthRepository you can change how permissions are managed by overriding its IManageRoles GetPermissions() and HasPermission() APIs to also inspect the Permissions that the Users Roles have assigned to them which you would need to maintain in an out-of-band table.
Overriding OrmLiteAuthRepository
OrmLiteAuthRepository implements IManageRoles so when needed you can cast IAuthRepository to IManageRoles, e.g:
var manageRoles = (IManageRoles)container.Resolve<IAuthRepository>();
You can override OrmLiteAuthRepository and implement your own GetPermissions() and HasPermission() with normal inheritance, e.g:
public class MyOrmLiteAuthRepository : OrmLiteAuthRepository
{
public MyOrmLiteAuthRepository(IDbConnectionFactory dbFactory) : base(dbFactory) { }
public MyOrmLiteAuthRepository(IDbConnectionFactory dbFactory, string namedConnnection = null)
: base(dbFactory, namedConnnection) {}
public override ICollection<string> GetPermissions(string userAuthId)
{
return base.GetPermissions(userAuthId);
}
public override bool HasPermission(string userAuthId, string permission)
{
return base.HasPermission(userAuthId, permission);
}
}

Authentication & Authorization in MVC5

I have recently started to explore ASP.NET MVC and came across a scenario. I want to have expert's opinion over its implementation approach in MVC
Scenario:
We have two users classes:
Normal users
Power users
Normal users can only enter transactional data which pertains to their work area. For example, if there exists two work areas (W1 & W2) and user 1 is mapped to work area W1 then he can only enter transactional data of W1. Whereas, if user 2 is mapped to both work areas (i.e. W1 & W2) then the user can enter transactional data of any of the areas.
Power users , as name suggest, are super user. They can enter transactional data of any work area and can change Master Data of the application as well.
I want to use Windows Authentication for user authentication and for authorization I want to have a table in DB where domain user ids(AD) of users are mapped to relevant work areas along with their user type (normal/power).
My question is how this could be done in ASP.NET MVC5. Any lead towards its solution or pointer to any relevant article/tutorial will be highly appreciated.
Further to this, if I want to generate dynamic menu (each menu item is mapped to corresponding Action) at the time of authentication based on the authenticated user type then how it can be done.
Thanks for your time.
Based on my understanding of your question, you want to authenticate users with Active Directory, then authorize with local authorization mechanism.
If so, you could use OWIN cookie authentication middleware in ASP.NET MVC 5.
It has few moving pieces, so I created a sample application at GitHub. The followings are the database diagram and two main classes.
OwinAuthenticationService
private readonly HttpContextBase _context;
private const string AuthenticationType = "ApplicationCookie";
public OwinAuthenticationService(HttpContextBase context)
{
_context = context;
}
public void SignIn(User user)
{
IList<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Sid, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
};
foreach (string roleName in roleNames)
{
claims.Add(new Claim(ClaimTypes.Role, roleName));
}
ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);
IOwinContext context = _context.Request.GetOwinContext();
IAuthenticationManager authenticationManager = context.Authentication;
authenticationManager.SignIn(identity);
}
public void SignOut()
{
IOwinContext context = _context.Request.GetOwinContext();
IAuthenticationManager authenticationManager = context.Authentication;
authenticationManager.SignOut(AuthenticationType);
}
Startup.cs
You also need to configure Startup for all those to happen.
[assembly: OwinStartup(typeof(YourApplication.Startup))]
namespace YourApplication
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/Account/Login")
});
}
}
}
Usage
Then you can start using [Authorize] attribute in Controller and Action methods.
[Authorize(Roles = "Power Users")]
public class UsersController : Controller
{
// ...
}

ASP.Net MVC5: How to redirect and show right error message when user does not have a specific role for action

after login user can go to any action but think when action is decorated with authorized attribute and role names are specific there. just refer a sample code.
public class HomeController : Controller
{
[Authorize(Roles = "Admin, HrAdmin")]
public ActionResult PayRoll()
{
return View();
}
}
suppose user Foo has no role like Admin or HRAdmin then what will happen when user foo will try to access PayRoll action ?
in this kind of situation i want to redirect user to my error page where i will show a friendly message to user. please guide me how to do it ?
do i need to write a custom authorized attribute from there i need to check user has those roles are not and then redirect user from there?
I don't know if that's the best way to do it, but here's how I did it:
using System.Web.Mvc;
namespace YourNamespace
{
public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
// Redirect to the login page if necessary
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?returnUrl=" + filterContext.HttpContext.Request.Url);
return;
}
// Redirect to your "access denied" view here
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new RedirectResult("~/Account/Denied");
}
}
}
}
Controller:
public class HomeController : Controller
{
[AccessDeniedAuthorize(Roles = "Admin, HrAdmin")]
public ActionResult PayRoll()
{
return View();
}
}
That's all you have to do if your User has its Roles defined correctly. If you are not using ASP.NET Identity to manage your users and roles, you will need some more code to make this work, in that case this might help you: How can I attach a custom membership provider in my ASP.NET MVC application?.

How do I configure the Users context/table?

With the new ASP.NET MVC 5 Preview released, how do I configure the Users context/table?
In MVC 4 I would just use my own User class and then point the WebSecurity initialize to it, tike this:
WebSecurity.InitializeDatabaseConnection(connectionString, "System.Data.SqlClient", userTableName, userIdColumn, userNameColumn, autoCreateTables);
I wish to add additional properties to the Users class - how?
I think, this can solve your issue:
In Models \ IdentityModels.cs you can redefine your own User model:
public class ApplicationUser : IdentityUser
{
/* identity field from database */
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Required]
public bool Internal { get; set; }
public string UserFullName { get; set; }
public string UserEmail { get; set; }
public ApplicationUser()
: base()
{
Internal = false;
}
public ApplicationUser(string userName)
: base(userName)
{
Internal = false;
}
}
now you can change mapping of defaults AspNet tables using OnModelCreating() overridding and ToTable() methode:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Change the name of the table to be Users instead of AspNetUsers
modelBuilder.Entity<IdentityUser>().ToTable("User");
modelBuilder.Entity<ApplicationUser>().ToTable("User");
modelBuilder.Entity<IdentityRole>().ToTable("Role");
modelBuilder.Entity<IdentityUserClaim>().ToTable("User_Claim");
modelBuilder.Entity<IdentityUserLogin>().ToTable("User_Login");
modelBuilder.Entity<IdentityUserRole>().ToTable("User_Role");
}
}
Finally you will see in the database the following tables:
User, Role, User_Role, User_Claim, User_Login instead of AspNetUsers, AspNetRoles, AspNetUsersRoles, AspNetUsersClaims, AspNetUserLogins.
Of course the User table will contain additional fields: UserId (int identity), Internal, UserFullName and UserEmail.
The UserStore and User classes are there to make EF based implementations easier, but you can always drop down and implement your own custom IUserStore and pass in your own DbContext.
I can provide a more detailed example if you need.
You can download a sample from https://github.com/rustd/AspnetIdentitySample. This is based on the ASP.NET MVC template that shipped with ASP.NET and Web Tools 2013 Preview Refresh (Supports English version of VS2013 Preview only) Once you have this Preview Refresh installed you can do the same for ASP.NET Web Forms and SPA applications.
Following are the steps to Run this project
Open the solution
Build and run
Register a user ---- Notice that the user registration field only has user name and password
Let's ask for a birthdate option from the user while registering an account.
Goto Nuget Package Manager console and run "Enable-Migrations"
Goto Models\AppModel.cs and uncomment BirthDate property in the MyUser class
Goto Models\AccountViewModels.cs and uncomment BirthDate property in RegisterViewModel
Goto AccountController and in Register Action and have the following code var user = new MyUser() { UserName = model.UserName,BirthDate=model.BirthDate }; //var user = new MyUser() { UserName = model.UserName };
Goto Views\Account\Register.cshtml and uncomment the HTML markup to add a BirthDate column
Goto Nuget Package Manager console and run "Add-Migration BirthDate"
Goto Nuget Package Manager console and run "Update-Database"
Run the application
When you register a user then you can enter BirthDate as well

ServiceStack: Get email from auth session when authenticating with Google

I am authenticating users via GoogleOpenIdOAuthProvider. I need to access the email address of the user that logged in. I have attempted to implement the Using Typed Sessions in ServiceStack code as-is.
So, I created a base class that my service inherits from:
public abstract class AppServiceBase : Service
{
//private CustomUserSession userSession;
protected CustomUserSession UserSession
{
get
{
return base.SessionAs<CustomUserSession>();
}
}
}
public class CustomUserSession : AuthUserSession
{
public string CustomId { get; set; }
}
The service has the [Authenticate] attribute on it. In my AppHost setup, I have configured auth like this:
Plugins.Add(new AuthFeature(() => new CustomUserSession(),
new IAuthProvider[] {
new GoogleOpenIdOAuthProvider(appSettings) //Sign-in with Google OpenId
}));
Once the user has authenticated, the service tries to access the auth session from the base class like this:
var x = base.UserSession.Email;
However, Email is always null. How can I access this value?
You will need to pull the data from the AuthProvider and set the value in the CustomUserSession. An example of this is shown in the SocialBootstrapApi sample
https://github.com/ServiceStack/SocialBootstrapApi/blob/master/src/SocialBootstrapApi/Models/CustomUserSession.cs#L50
Override OnAuthenticated, find the GoogleOpenIdOAuthProvider to get to the email address.
Another example is shown at ServiceStack OAuth - registration instead login

Resources