I am using MongoDB to store users and passwords (instead of sql). I have my own mechanism for assigning roles to users. I would like to decorate my controller actions with roles, as follows:
[Authorize(Roles = "Administrators")]
My login code looks like this:
if (mongo.AuthenticateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
}
What is the simplest way for me to 'stamp' a users roles onto the user when they first login (the database will provide me with the role names, I just need to set them within the users context). I guess I'm looking for my code to look something like this:
if (mongo.AuthenticateUser(model.UserName, model.Password))
{
if ((mongo.IsAdmin)
{
// How do I grant the admin role???
SomeSortOfUserContext.Add('Administrators');????????
}
FormsService.SignIn(model.UserName, model.RememberMe);
}
Add roles to User Principal in Application_AuthenticateRequest in Global.asax.
Check this out;
Related
Here is project that uses Web Service for get or set data on database.
For login method i send username and password, if it is correct web service returns role and id.
How can i set this role for this user?
I must check this role for each action.
To allow each user by their roles you can use:
[Authorize(Roles = "Admin")]
public class SomeController : Controller
or if you want to, you can just allow each method individually:
[Authorize(Roles = "Admin")]
public async Task<IActionResult> Index()
I didn't quite get what you were asking, but i read the title again and if u want to assign a role to a user use this:
await _userManager.AddToRoleAsync(user, "Guest");
Being "Guest" the role.
I think you should use this on the register method instead of the login.
Hope this helps.
Use Role based Authorization filter some thing like this
[Authorize(Roles = "Administrator")]
public class AdministrationController : Controller
{
}
I hope someone will be able to put me on the right track, been trying to resolve this now for hours.
I am currently in the process of redeveloping a web application and I would like to use the MVC4 attributes for managing access to the various parts of the application.
The issue I am having is that the Authentication & Permissions are all handled by middle-ware applications that the web app has to interface with.
I was wondering if even with this restriction would I be able to use the security attributes & letting the web app know that the user is Authenticated.
Yes, you will be able to use existing Authorize attribute. All you have to do is write a custom Membership and Role providers that will use your existing services instead of relying on the default SQL database.
If you don't want to go through all this hassle you could also write a custom authorization attribute (deriving from AuthorizeAttribute) and inside the AuthorizeCore method call your service to check whether the current user has the desired roles.
Definitely. Not only is it possible, but also it's pretty easy. And if you can think of ASP.NET Roles as "activities", then you don't need to derive anything; everything you need is built in.
These examples assume securityService is the service that communicates with your middle-ware applications, and has two methods, GetUser and GetUserRoles:
Your Login action method
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (!ModelState.IsValid) return View();
var user = securityService.GetUser(model.Username, model.Password);
if (user == null)
{
ModelState.AddModelError("", "Username or password are incorrect.");
return View();
}
FormsAuthentication.SetAuthCookie(user.Username, model.Remember);
return Redirect(returnUrl);
}
In your Global.asax.cs
protected void Application_AuthenticateRequest()
{
if (Request.IsAuthenticated)
{
string username = User.Identity.Name;
string[] roles = securityService.GetUserRoles(username);
IIdentity identity = new GenericIdentity(username);
Context.User = new GenericPrincipal(identity, roles);
}
}
That's it. Login handles the authentication (when the user logs in), while Application_AuthenticateRequest handles the authorization (on every request). You then proceed to decorate your action methods with Authorize(Roles = "XYZ") making sure "XYZ" matches what comes back from your GetUserRoles method.
I can setup custom membership easily enough, but what if I need two sets i.e. admin for control panel and registered for logged on customers. This would mean two seperate tables to get users from. My question is how can I integrate the two to control through 1 custom membership and how can I authenticate on the controller for the 2?
You wouldn't separate users this way, you'd implement a custom role provider and allocate these roles to the user. So say you have created two roles admin and user you'd set an attribute to your controller like so:
Admin page controller
[Authorize(Roles = "Admin")]
public ActionResult AdminAction() { }
User page controller
[Authorize(Roles = "User")]
public ActionResult UserAction() { }
If you wanted your administrators to view all logged in user pages, you'd simply just assign the user role to your administrators.
Does MVC.NET handle Roles using cookies, or does a controller check with the Role Provider on each request? Consider this code:
[Authorize(Roles="CommentsModerator, SiteAdministrator")]
public ViewResult ApproveComment(int commentId) {
// Implement me
}
Are roles set as a cookie when a user first lots on, or will the Authorize attribute check with the Role Provider for each call to this action?
If it uses cookies, it'll be fast. However, it would be tricky to handle the case where a user is removed from a role unless they log out to delete the cookie.
The controller will check the role provider for each request.
You can override the default behavior with:
http://msdn.microsoft.com/en-us/library/system.web.security.roles.cacherolesincookie.aspx
i'm new to asp.net mvc and starting the following project. The company wants an intra-net website for various groups of people to upload files to a database, run reports off the it and amend data in several master tables in the database. The company use Active Directory and do not want the users to log in again to use the web site. The website will have different sections for various groups and the user's access to a particular page should be controlled from a database.
So far this is what i've come up with
changed the membership provider to link to the active directory server (based on Mike's blog post)
removed AccountController and the Views/Account folder
created a custom authentication class based on this link
I need to pull from a table in the database, based on user's AD id, his "role" (int), then cast it into the relevant SiteRoles. Would implementing this query in CustomAuthorizeAttribute be adviseable? is there a better place to pull the data from the table and store it somewhere so it can be reused rather than having to run a database query every time AuthorizeCore is called (which will happen whenever a user invokes a controller/action)?
A custom AuthorizeAttribute is definately the way to go as it will be applied before all other action filters.
Kindness,
Dan
I would use the out-of-the box ActiveDirectoryMembershipProvider rather than a custom attribute (because reinventing the wheel is generally bad, and reinventing the wheel in the area of security is bad to the point of incompetence in most cases), and the AzMan Role Provider to map AD groups and accounts to app roles.
This pairing gives you far more features out of the box (e.g., standardized GUI interface for permissions) than custom code, and is probably more secure, too.
You could do everything you want using the MVC provided FormAuthentication. Just create your custom ValidateLogOn method in the AccountController. Example:
public ActionResult LogOn(string userName, string password, bool rememberMe, string returnUrl)
{
if (!ValidateLogOn(userName, password))
{
return View();
}
FormsAuth.SignIn(userName, rememberMe);
Session["userlogin"] = userName;
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
Where your ValidateLogOn will be something like:
private bool ValidateLogOn(string userName, string password)
{
if (String.IsNullOrEmpty(userName))
{
ModelState.AddModelError("username", "You must specify a username.");
}
if (String.IsNullOrEmpty(password))
{
ModelState.AddModelError("password", "You must specify a password.");
}
/*
* Do your LDAP Validation stuff (DB queries, etc) here.
*/
}