I am using asp.net core default web site template and authentication selected as individual user account. How can I create role and assign it to user so that I can use role in controller to filter the access.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Carriage Return (ASCII chr 13) is missing from tex
- MVC-Routing,Why i can not ignore defaults,The matc
- Why am I getting UnauthorizedAccessException on th
I use this (DI):
I created a action in the account controller that call a function to create the roles and affect the admin role to a default user (You should probably remove the default user in production):
After you could create a controller to manage roles for the users.
Temi's answer is nearly correct, but you cannot call an asynchronous function from a non asynchronous function like he is suggesting. What you need to do is make asynchronous calls in a synchronous function like so :
The key to this is the use of the Task<> class and forcing the system to wait in a slightly different way in a synchronous way.
In addition to Temi Lajumoke's answer, it's worth noting that after creating the required roles and assigning them to specific users in ASP.NET Core 2.1 MVC Web Application, after launching the application, you may encounter a method error, such as registering or managing an account:
A similar error can be quickly corrected in the ConfigureServices method by adding the AddDefaultUI() method:
Check
https://blogs.msdn.microsoft.com/webdev/2018/03/02/aspnetcore-2-1-identity-ui/
and related topic on github:
https://github.com/aspnet/Docs/issues/6784 for more information.
And for assigning role to specific user could be used IdentityUser class instead of ApplicationUser.
The following code will work ISA.
My comment was deleted because I provided a link to a similar question I answered here. Ergo, I'll answer it more descriptively this time. Here goes.
You could do this easily by creating a
CreateRoles
method in yourstartup
class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so.and then you could call the
CreateRoles(serviceProvider).Wait();
method from theConfigure
method in the Startup class. ensure you haveIServiceProvider
as a parameter in theConfigure
class.Using role-based authorization in a controller to filter user access: Question 2
You can do this easily, like so.
You can also use role-based authorization in the action method like so. Assign multiple roles, if you will
While this works fine, for a much better practice, you might want to read about using policy based role checks. You can find it on the ASP.NET core documentation here, or this article I wrote about it here