Whats the different between Membership.GetUser and Profile.GetProfile if i wants to return a specific users information?
Membership and Profile are two completely different things. The Membership.GetUser providers authentication for an application and designates if the user is logged in, while the Profile is something that can be used to describe a user given properties that have been defined in the web.config that are type safe and customized for an applicaiton.
EDIT:
To follow up a little more, a User object that is returned from Membership.GetUser() has information like username, password, security question / answer.
Profile information can contain anything that you want to know about a user, such as first name, last name, DOB, favorite type of ice cream, etc. Just as long as you set this up in the web.config:
<system.web>
<profile>
<properties>
<add name="firstName" type="string"/>
<add name="lastName" type="string"/>
<add name="DOB" type="DateTime"/>
<add name="favoriteIceCream" type="string"/>
</properties>
</profile>
</system.web>
The membership is the username, password and optionally a secret question / answer. You get a MembershipUser back from Membership.GetUser().
The profile is your own customised profile object that you can configure to store whatever information you want in it.
Membership.GetUser will return the user entry - e.g. the user with name, first name, e-mail address and so on.
Profile.GetProfile will return a given user's profile settings, e.g. his preferences, config settings etc.
Related
web.config
<roleManager enabled="true" defaultProvider="SqlRoleManager">
<providers>
<clear />
<add name="SqlRoleManager"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="DefaultConnection"
/>
</providers>
</roleManager>
in asp.net mvc 5, i'm trying to detect the role of the current user so i can redirect him to a page specific to it's role but
in my controller
if (Roles.IsUserInRole(User.Identity.GetUserName(), "superadmin")
or
if (Roles.IsUserInRole(User.Identity.Name, "superadmin")
the both are not true, i'm sure that i'm logged bec User.Identity.GetUserName() is displaying my login
Trying to debug, i found that Roles.GetRolesForUser() is empty, i've checked online resources but still no solution
Further debugging shows that Roles.GetAllRoles() is also empty, but my AspNetRoles table has 5 records.
I've looked at AspNetUserRoles and i found my current User id assigned to specific role id
and i've successfully run aspnet_regsql.exe to add all features but still cannot get the Roles
i think aspnet_regsql.exe is for web forms (i'm not sure)
I'm on my phone so can't double-check, but I'm sure IsUserInRole() will accept a single argument like IsUserInRole("superadmin") to check the current user in a session. I would remove the username part because you're checking the current user and not a different named user. It's quicker and will at least check and eliminate one part of the logic.
How are you seeding the roles?
I'm recieving two strings: the username and the password, based on which, I'm retrieving and instance of AspNetUser, which has the corresponding fields. I want to produce the corresponding Id but only if the name and pass check out. The former is simple because it's in plain text.
How can I, given the provided password, verify that the hash value is correct?
I have looked at the code in the default template for a few hours but I can't get my head around it. Based on this page, I've created my own HASHes but the one I'm getting differs from the on in the DB, so I'm guessing that I'm doing it wrong or that they are adding some magic part before hashing it.
My: E8B9C259EAB04BBB67B2D67AF5745B
DB: AFczTgO67ViTWwZNejEiTyKRg5s96x5mOmwFFBj7yRUpys/5duOw0q6I6imCm1t1hQ==
See above, can you spot the difference...? The password used is "Abc123()", in case it matters.
Am I barking up the wrong tree when I try to use MD5CryptoServiceProvider? Is there a default string that's being jacked into the source before the hash's being computed?
If there are comments regarding the best practices, I'm open to them, of course. Bear in mind, however, that the security issues being my weak point, have bothered me for a long time so this is the way I want to go to understand the concept, down to bits and bolts. If possible, that is.
I can optionally use the facility that MS provided for me but I haven't got that right yet, neither. It appears to me like a lot of code doing "something here, something there".
<system.web>
<membership defaultProvider="donkey">
<providers >
<clear/>
<add name="donkey" passwordFormat="Hashed" />
</providers>
</membership>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
<customErrors mode="Off"></customErrors>
<httpRuntime targetFramework="4.5.2" />
</system.web>
The Membership class you're using provides the static ValidateUser method:
Verifies that the supplied user name and password are valid.
public static bool ValidateUser(
string username,
string password
)
public void Login_OnClick(object sender, EventArgs args)
{
if (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text))
FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked);
else
Msg.Text = "Login failed. Please check your user name and password and try again.";
}
I cannot find any information on how to implement custom FormsAuthenticationModule.
Specifically, I want to implement a MyFormsAuthentication that mirrors most features of FormsAuthenticationModule, or child of FormsAuthenticationModule
<httpModules>
...
<add name="FormsAuthentication"
type="System.Web.Security.FormsAuthenticationModule" />
...
</httpModules>
MyFormsAuthentication can be used by the element in web.config, instead of the default FormsAuthenticationModule:
<authentication mode="Forms" />
The reason is that I want to support the domains format below:
Set A
a.domain.com
a.x.domain.com
a.y.domain.com
Can share cookie within set A.
Set B
b.domain.com
b.x.domain.com
b.y.domain.com
Can share cookie within set B.
Cookies (including Forms Authentication cookie) cannot be shared between domains of set A and set B, but use the same code base.
Current implemention
FormsAuthenticationTicket is used to generate forms auth cookie.
Any idea, or better solution?
https://msdn.microsoft.com/en-us/library/aa480476.aspx
How can I configure ELMAH to display only for certain people without default ASP.NET authorization roles manager?
I (as well as many others, I think) use my own authorization logic and build my projects from zero without using provided templates. I want to log errors but it seems that it is impossible to configure ELMAH (somehow override functionality) to make it work with some other authorization or even to make it work only for particular IP addresses.
Since I will have access to web.config I tried to change these values in order to NOT display elmah by default.
<add key="elmah.mvc.disableHandler" value="false" />
<add key="elmah.mvc.disableHandleErrorFilter" value="false" />
<add key="elmah.mvc.requiresAuthentication" value="false" />
And when I want to view errors switch them from true to false and see errors, then switch back. But it seems that when I change these values all logs are erased.
What can I do?
I think the easiest approach would be to make some minor alterations to your custom authorization so the ELMAH authorization will work.
Option 1: Set the FormsAuthentication cookie on login. This way, in the web.config the allow users="username" should work. On successful login you can set the cookie with
FormsAuthentication.SetAuthCookie(theUsername, true).
The ELMAH authorization would look something like:
<location path="elmah.axd" inheritInChildApplications="false">
<system.web>
<authorization>
<allow users="theUserName" />
<deny users="*" />
</authorization>
</system.web>
...other config settings
</location>
Option 2: If you are using putting users into roles, you can override the default role provider to use the function you made to get roles. This way is a little more involved but then lets you harness role-basing authentication in the web.config, which is really nice for securing things like static file (.pdf etc) delivery. I can add code for this if interested.
I was using the ASP.NET Identity Framework, so this answer is regarding that setup. I also used the Elmah.MVC package in NuGet. I edited the following lines in web.config. (you need to supply your own user name in the allowedUser setting)
<add key="elmah.mvc.requiresAuthentication" value="true" />
<add key="elmah.mvc.allowedRoles" value="*" />
<add key="elmah.mvc.allowedUsers" value="your_user_name" />
It appears that ELMAH does get the authentication information from the current thread principal, which the ASP.NET Identity Framework will establish on your behalf upon login.
It doesn't matter how the system gets the username or roles in this case. Whether it be from the built-in providers, a provider you implement yourself, or if during your custom authentication you populate this information yourself. All it takes is to manually set the principal during something like the Application_PostAuthenticationRequest event. This should give you the jist of it.
protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
//Obtain username and roles from application datastore and use them in the next line
Thread.CurrentPrincipal = new GenericPrincipal(
new GenericIdentity("userNameHere"),
new string[] { "Admin", "CanDeleteStuff", "CanEditStuff", "OtherRole" }
);
}
This will let you use something like this in your web.config
<location path="elmah.axd" inheritInChildApplications="false">
<system.web>
<authorization>
<allow roles="Elmah"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
Not to mention being able to use User.IsInRole("CanEditStuff") in your code.
How do I go about Authorization in MVC 2?
I want to use AD groups/roles rather than the default that is provided. That seems to be "AspNetSqlMembershipProvider".
Anyway I put :
[Authorize(Users = "username")]
public ActionResult About()
{
ViewData["Welcome"] = "Welcome About";
return View();
}
And then loading the page gives me: The connection name 'ApplicationServices' was not found in
the applications configuration or the connection string is empty.
Line 34: <providers>
Line 35: <clear />
Line 36: <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
Line 37: </providers>
Line 38: </membership>
I read this stackoverflow, but after creating a custom class AuthorizationAttribute extending ActionFilterAttribute ContextCache, IoC and a number of other things could not resolve, and not really sure where to go from there. I also read this stackoverflow and it suggests going about it differently, starting to get confused.
How do I go about using AD groups rather than AspNetSqlMembershipProvider in MVC app ?
Bonus question: Say I have a "Edit" button a page. Can I add logic to decide whether to render this button based on the Authorization ?
Thank you for your help.
Edit: some further information.
I do not intend to block or allow ALL access to this site.
I intend to have 3 basic user groups differentiating level of access, i.e. Super Admin, Admin,
Basic Access.
There will be no log in form, when the user hits the site we will check which group the user is a member of- then the page renders based on that.
So for example, user 'bob' in 'Basic Access' group will hit the page and buttons/actions like "Edit", "Delete" are disabled, so basically a read only group. But user 'jim' in group 'Super Admin', has all actions/buttons available to him. How could I achieve this ?
You should look into Windows Authentication
Still use the Authorize attribute on your controllers/actions, but configure your site to use Windows Authentication instead.
Bonus answer: To check authentication and authorization in code, you can use one of the following from a controller:
this.User.Identity.IsAuthenticated
this.User.Identity.Name
this.User.IsInRole("roleName")
The answers to use Windows authentication work great, with the following caveats.
First, the server must be joined to your Domain. And it has to have free AD access if there are any firewalls in place.
Second, you have to be ok with having a popup dialog for login, rather than using a form based login.
If you need AD with forms login, then there's more work involved. Can you be more specific about your needs?
well, you can restrict access to the site via webconfig.
<authentication mode="Windows" />
<authorization>
<allow roles="[YOURADSERVER]\[YOUR AD GROUP]"/>
<deny users="*"/>
</authorization>
this will block any others not listed in the given ad groups.
in IIS you will need to disable anon access and enable windows auth