Forms Authentication — Where are roles stored? - c#

Where are the roles below stored?
Roles.AddUserToRole(user.UserName, "customer");
Roles.IsUserInRole(user.UserName, "admin");
If I add a user to a role using the code then the membership persists. I cant see a built in database in my project and I have not manually specified a database. Am I going mad?

Information about role storage may be picked from web.config
This db might have been created for you by asp.net itself, and is called
aspnetdb
Please look at this as well:
https://msdn.microsoft.com/en-us/library/system.web.security.roles(v=vs.110).aspx

Related

Update user's membership role

I am using asp.net MVC 5 identity 2.0
The administrator is able to change user’s role but used must re-log to see the changes. First thought was to re-log user manually but I failed. After that I thought of dynamically changing user’s role or something else. Could you provide me the right way?
I set user’s role using UserManager.AddToRolesAsync
I have tried a lot of things like:
var memberUser = Membership.GetUser(user.UserName.ToString());
if (memberUser.IsOnline)
{
FormsAuthentication.SignOut();
}
or also try to clean up my cookies.
I dunno how I can sign out another user.
Also I have read articles like these
http://w3facility.org/question/mvc-5-addtorole-requires-logout-before-it-works/
How do I forcefully propagate role changes to users with ASP.NET Identity 2.0.1?
How to force logout user when his/her username is changed by another user?
ASP.net Identity 2.0 Sign-out another user
Have a look at the answer provided by Hao Kung on this post he describes exactly how to solve this using the SecurityStamp .
https://stackoverflow.com/a/19505060/1454538
So the primary purpose of the SecurityStamp is to enable sign out
everywhere. The basic idea is that whenever something security related
is changed on the user, like a password, it is a good idea to
automatically invalidate any existing sign in cookies, so if your
password/account was previously compromised, the attacker no longer
has access.
In 2.0.0 we added the following configuration to hook the
OnValidateIdentity method in the CookieMiddleware to look at the
SecurityStamp and reject cookies when it has changed. It also
automatically refreshes the user's claims from the database every
refreshInterval if the stamp is unchanged (which takes care of things
like changing roles etc)
This should get you going.

Authorization/Roles in MVC5

I'm having trouble using authorization/roles in MVC5 (VS2013).
Authentication works pretty much out of the box (that's to say just by using Visual Studio to create the default MVC project). I change the DefaultConnection connection string to a valid (but non-existent) database. I then register a new user and the database is automatically created, with tables such as AspNetUsers and AspNetRoles.
However, I can't seem to do anything with roles. The first thing to do seemed to be to add a role with C# code like:
Roles.CreateRole("Admin");
I get an exception with the message:
'The Role Manager feature has not been enabled.'
I enable it in web.config with:
<roleManager enabled="true"/>
And now get the exception:
'Unable to connect to SQL Server database.'
This used to work very easily with System.Web.Security.SqlRoleProvider, but not with the new provider that comes as default with MVC5. There are lots of very complex articles on this, but it seems to me that it is something so essential and straightforward that there must be a simple way to get it working.
Many thanks for any help.
I've solved this now. It turns out that the Roles class is completely irrelevant to role management in MVC5, at least in terms of the out-of-the-box configuration.
The Roles class and Membership class are still there, with the Provider configured to SqlMembershipProvider.
However, this is NOT the provider used by the AccountController, which does not use the Membership class at all; it uses Microsoft.AspNet.Identity.UserManager.
While the generated AccountController provides plenty of examples of using UserManager, it does nothing related to roles.
The equivalent class for Roles is Microsoft.AspNet.Identity.RoleManager. There is full documentation for this in MSDN
I suggest referring to this article as it shows how you can create roles. Once you've created whatever roles are required, you can use the UserManager.AddToRole or UserManager.AddToRoleAsync method to add a user to a particular role.

Custom User and Roles with ASP.NET MVC3

I have a ASP.NET MVC site with a CAS server set up as the authentication type. I also have a separate database with a Users table and a Roles table (with a User being related to one or more roles). A User is only able to log into the system if the Username is both in the User table and on the CAS system. I have this solution working.
My problem is i now need some form of trigger on User.IsAuthenticated so i can track the current User (from my database), without the possibility that i am trying to allow tracking of a User that has logged out. What I've been thinking is i need to add the User to the HttpContext but i am not sure how to trigger the clearing of the User if the CAS session times out or if the User Logs out.
I also wish to have some functionality such as User.IsInRole (again using my database, not ASP.NET) but am not sure how to go about implementing this. I suppose if i can successfully add the User to the HttpContext then a IsInRole method would simply be a User.Roles.Contains(string role) method but how can that then be used if i wish, for example, to use a method with the DataAnnotation [Authorize(role = "ExampleRole")].
I have looked at questions such as How do I create a custom membership provider for ASP.NET MVC 2? but this doesn't work for me (possibly to do with me using the CAS authentication?)
Any guidance or background reading would be appreciated as i'm really not sure where i should even start. I have read up on GenericPrinciple, IPrinciple and IIdentity but I'm struggling to see how i can apply them to my current project.
Ended up with a custom Authorise Attribute that uses the CAS logon to check the user exists in my database. It also checks the roles of that user. I also used a static class to save the current user in the session with a logout method that abandons the session when the user logs out.
I have kind of a two parter for you. This link does a really good job of explaining how to replace the HttpContext User with your own object: http://bradygaster.com/custom-authentication-with-mvc-3.0
His approach uses MVC filters, but you can also catch the Authentication event in the Global.asax file. Using the forms system with your own implementation can be trivial or not depending on what you're doing, but it boils down to calling FormsAuthentication.SetAuthCookie and .SignOut, amidst your own logic.
public static void FormsLogin(this User user, bool persist)
{
FormsAuthentication.SetAuthCookie(user.DisplayName, persist);
user.AddHistory("Login event.", HistoryType.Login, "SYSTEM");
Users.OnUserLogin(user);
SetLastActivity(user);
}
public static void FormsLogout(this User user)
{
FormsAuthentication.SignOut();
}
Lastly, once you've got the login stuff working out, you can use your own more complex permission system by making a custom Auth Attribute. I remember piecing this together from some other answers and articles but I can't seem to find the sources at the moment, I will try and edit with sources for credit where it's due, if I find them. For now, all I can offer is this gist which offers up one of the attributes I use: https://gist.github.com/1959509
Keep in mind the only really relevant part there is the override of OnAuthorization, which does the actual work.

Forms Authentication for different roles?

I am developing a website in which I'm using forms authentication.
We have 2 log in pages: one for user, another for admin.
I added this code into webconfig file for user.
<forms loginUrl="Login.aspx" defaultUrl="Home.aspx" >
I am using this code for user side when user successfully logged in.
FormsAuthentication.RedirectFromLoginPage (UserName.Text, chkPersistCookie.Checked)
I am not using the default user membership database. I have my own database in SQL Server 2005.
I want same thing for admin, but the default url is Admin.aspx & login url is adminlogin.aspx for admin.
How can i assign in web config file for admin? Is it the right way to do that or any one have some better concept for that?
I used This line of code and this worked for me.
FormsAuthentication.SetAuthCookie(txtUser.Text, true);
Response.Redirect("Admin.aspx");
Putting admin files to a folder and creating a web.config file in it, is an option. You can probably override the config rules there.

Asp.net Login - Working with user data

I'm making a simple page and i need a login interface for users.
I want users to login to the page and when he is logged in he gets alot of data from the database that is signed to him alone. I did this before using very simple datatable holding the username, crypted password and the uid. When the user logged in the site i set the uid into a session so i could use it when i was selecting from the database..
This is probably not a safe way....easy to crack ?
Better way would be using the asp.net login id...?
What is the best way to do this, should i have all the user info in the ASPNETDB.MDF, and does that database work when i deploy the site on a server ?
Can i use ASP.NET Configuration when i have deployed ?
[Edit]
How can i use the asp.net login to get the userid of the current logged user so i can do sql querys for him ?
I think you should read more on "ASP.NET authentication" - regarding how to implement user login/logout/get userid etc. And on "ASP.NET authorization" - regarding security and access and come back with certain questions. There's standard mechanism for this.
Start with MSDN:
http://msdn.microsoft.com/en-us/library/eeyk640h.aspx
http://msdn.microsoft.com/en-us/library/wce3kxhd.aspx
The ASP.NET membership provider will likely be your best approach as it handles all of the basic plumbing which you need. The tables are quick to setup with the ASP.NET SQL Server Setup Wizard (C:\Windows\Microsoft.NET\Framework\v2.0.50727\Aspnet_regsql.exe) and the combination of the Configuration pages and out of the box login controls will get you up and running quickly. I would recommend going down this path.
Regarding one of your specific questions, the logged in user's Id is stored in the ProviderUserKey. This is the value which maps to the UserId in the membership tables like aspnet_Users and others. Here's how you get the value:
using System.Web.Security;
//ProviderUserKey is an object.
//You will likely want to convert to string or Guid
MembershipUser user = Membership.GetUser();
Object userId = user.ProviderUserKey;
There really is nothing wrong with the way you are doing it, although there are easier methods to do it.
If you are creating a login hash, and storing it in session, the users have no access to that data.
When you create a session state, all that gets sent down in a cookie is a GUID that refers to their own session, and not any of the actual data. Because of this, you can generally assume the data is protected and users can't get access to anyone else's data.

Categories