I have certain routes that I need to protect from users that are not admin.
For example
http://myapp.com/clients
returns all the clients but is only for the administrator.
However
http://myapp.com/client/treutel_breitenberg
Should be available to them if they are logged in.
What is the best way to achieve this
You're going to need roles and a middleware, and there are many ways to do it. First you need to create an admin role, so some of your routes will only be available for someone who has the admin role. For that you can follow this laracasts tutorial : https://laracasts.com/series/whats-new-in-laravel-5-1/episodes/16
You can also use a plugin to manage roles, like Zizaco's Entrust, it's built-up good, tested by a lot of users and easy to use : https://github.com/Zizaco/entrust
Next, to answer your question for the routes you can proceed like that :
Route::group(['middleware' => ['admin']], function () {
Route::group(['prefix' => 'admin'], function () {
Route::get('/your-path', 'YourController#yourMethod')->name('yourRouteName');
}
}
Any route within these two groups will need to be authenticated as admin and will return 'admin' prefix in your route, like so : www.yourwebsite.com/admin/your-path
If you don't use a plugin, you'll need to create your middleware to handle admins only.
Related
Is there a way to disable or enable sign ups for a specific application which is independent of the “Disable Sign Ups”-toggle in the dashboard for login with passwordless email (Authentication/Passwordless/Email)?
Only partly.
It's possible via Pre-User-Registration Hook and/or or Rule with some caveats.
Pre-User-Registration Hooks :
https://auth0.com/docs/customize/hooks/extensibility-points/pre-user-registration
Something like this:
module.exports = function (user, context, cb) {
return cb(new PreUserRegistrationError('Denied user registration in Pre-User Registration Hook', 'You are not allowed to register.'));
}
};
Here you can just fail the registration at all times.
Problem with Hooks is that that the Pre-User-Registration Hook does not trigger for social connections / federation, only Database Connections and Passwordless.
Alternatively via Rule:
https://auth0.com/docs/customize/rules
This will always work, but the downside is that the user gets created in Auth0, they will just not be able to further proceed.
In the Rule you basically check the number of logins, if it's 0, you know that it's a new user, and block the login that follows right after user creation (signup) as well as any other time.
Example rule:
https://auth0.com/rules/disable-social-signup
Related earlier answer of mine regarding this, in the Auth0 forum:
https://community.auth0.com/t/disable-signup-from-auth0-ui-and-enable-social-login/29227/2
I just figured out I can create another 'Tenant' (from the dashboard) with a different setting for Sign Up from the dashboard :-)
You could implement a custom Universal Login SPA for sign-up/in that only allows users to sign-in. Pre-registration hook to safeguard against people bypassing the UX.
In asp.net core it is very easy to define the razor pages authorization for pages and folders as follows:
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Contact");
options.Conventions.AuthorizeFolder("/Private");
options.Conventions.AllowAnonymousToPage("/Private/PublicPage");
options.Conventions.AllowAnonymousToFolder("/Private/PublicPages");
});
My problem is that I want to use roles in my project but I can not find a way to define which roles are allowed to view the contents of the page.
I tried to use the Authorize attribute but it does not work with Razor Pages.
The AuthorizePage can take a second parameter which can be used in order to define the policy which will be used in order to determine if the current use can see the specified page or not. I used it as follows:
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Admin"));
});
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Index", "RequireAdministratorRole");
});
The problem is that it still does noe work. It acts like I have not defined the policy. When I am logged I can see the page and when I am not logged it redirects me to the loggin form.
Is something else that I have to do in order to make it work?
I found what is wrong. In order to apply the changes after I remove the user from the role, I have to logout and login again so that the framework will refresh what the user allows to view.
This is really a problem because if a User has the admin role and for some reason we want to stop him from accessing sensitive data, we cannot stop him until he logs off.
Is there a way to refresh the user’s permissions when I remove a role from his account?
Restarting the application did not remove his permission. The only way to refresh his permissions is when he logs out.
This is due to the user's cookie still being valid. Here is more explanation to it here with a solution. Although it is in ASP.NET, the same concepts should apply for your Razor Pages project:
Refresh current user's role when changed in ASP.NET identity framework?
As to your latest question of
Is there a way to refresh the user’s permissions when I remove a role
from his account?
Yes you can refresh your logged in user using the SignInManager RefreshSignIn method.
As per the official documentation the method will
Signs in the specified user, whilst preserving the existing AuthenticationProperties of the current signed-in user like rememberMe, as an asynchronous operation.
I am trying to understand on how to extend the wolkenkit auth layer.
Say i want users with different roles: normal, moderator and admin.
normal users can see and modify their own content, but aren't allowed to modify content from other users.
moderator users are allowed to modify all entries, but don't have permission to delete anything than their own content.
admin users can modify and delete everything.
There are also unauthenticated guest users who can read everything but modify nothing.
Reading the docs for Write model: Configuring authorization i can model the guest/normal use case by writing something along the lines of:
const initialState = {
isAuthorized: {
commands: {
issue: { forAuthenticated: false, forPublic: false }
},
events: {
issued: { forAuthenticated: true, forPublic: true }
}
}
};
For my requirements i would need additional roles defined in this object. Something like { forModerator: true, forAdmin: true }.
There is also Granting access from a command to change permissions at runtime, but i am not sure if that would work. Even if it does, that feels quite hacky.
Is this somehow possible?
Disclaimer: I am one of the developers of wolkenkit.
To cut a long story short: No, right now unfortunately this is not possible, but this feature is on our roadmap. At least today, I can't tell you when this will be available.
Your best option would be to do it on your own. One way to do this might be to use your identity provider to include a moderator claim in the JWTs of the moderators, and then handle this in the command handler appropriately.
In the command handler you have access to the token by
command.user.token
so you can get the claims as needed. I'm very sorry, that there is no better answer right now :-(
so!
I have a question: how to allow access some part of module only for adminisitrator, for example.
For example, I have module album. It has controllers index, delete, add, edit, full. I want full and index controller be available for all roles, but edit, delete and add action only for administrators.
What module I have to use to do that? I found Zend\Authentification.
Table is: username, password, role.
How to authentificate user?:
// do the authentication
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
// success: store database row to auth's storage
// system. (Not the password though!)
$data = $authAdapter->getResultRowObject(null, 'password');
$auth->getStorage()->write($data);
$this->_redirect('/');
} else {
// failure: clear database row from session
$this->view->message = 'Login failed.';
}
After that I will get access to user data, for example, by:
Zend_Auth::getInstance()->getIdentity()->username;
So, in action, in which I want to restrict access I just need to use:
if(Zend_Auth::getInstance()->getIdentity()->role == admin) {
redirect("auth/login");
}
Right?
The questions:
Is my suggestion about how to check user role in each contoller correct?
Do I understand correctly how to work with Zend\Authentification and restrict access to some actions? So in future I will just use same for each action, right?
Additional question: Does Aclmodule uses for managing permissions? So Acl is needed to help Zend_Auth with permissions, right?
To be able to do this you have to build or implement an ACL (Access Control List). You can also use a third party solution in combination with the earlier mentioned Zend_Auth (or any other authentication module). You can read more on Zend ACL here: Zend ACL introduction
You could for example also take a look at BjyAuthorize. This ACL module provides a complete authorization solution for your application but depends on ZfcUser for user authentication and registration. It might be a good way to get started.
If you are done building or implementing BjyAuthorize you can easily tie your access permission checking to your routes (but there are many other ways). You can see how this works here on the BjyAuthorize GitHub page
These modules will teach you a lot about how authentication and authorization can be build into your Zend Framework 2 application.
I installed the yii user extension and now i am wandering how i can add an extra role. I added a new column in the User db table and edited the UserModule like this:
public static function isEmployee() {
if(Yii::app()->user->isGuest)
return false;
else {
if (!isset(self::$_employee)) {
//check to see what kind of user we got and include admin for all
if(self::user()->type)
self::$_employee = true;
else
self::$_employee = false;
}
return self::$_employee;
}
}
and then when i try calling this in the rest of my site it dose not seem to work
'visible' => Yii::app()->user->isEmployee()
What i am doing wrong or what would be the best way to add an extra role that i can call on the site as above.
I don't know which extension exactly you installed - but you confused it with the user component. The user component is what you can access through Yii::app()->user. It's a CWebUser object by default. You can create your custom class WebUser extends CWebUser in the components/ directory. You would configure this as user component in your main.php config file.
'components' => array(
'user' => 'WebUser',
),
Then you move your isEmployee() method into that class. As you didn't provide any details on which extension you used, i can not really help you how to get that role check right. But i wonder if you shouldn't rather use a RBAC based solution. It allows you to create Roles and assign them to users. There are also several extensions that help you to manage roles and users.
Yii User is not meant for adding roles to users, it only handles user account management.
You may install an additional extension like rights, auth or srbac (see list) which provides a web-interface for this task.