I have some problems with getting my website to log out the authenticated user automatically when the session ends (the user closes the browser).
This is what I have in my web.config:
<authentication mode="Forms">
<forms name="AuthCookie" protection="All" loginUrl="~/default.aspx" path="/" cookieless="UseCookies" timeout="2592000"/>
</authentication>
<authorization>
<allow users="?" />
</authorization>
<membership defaultProvider="ASPPGSqlMembershipProvider" userIsOnlineTimeWindow="20">
<providers>
<clear />
<add name="AspNetSqlMemberShipProvider" applicationName="umbraco4" type="System.Web.Security.SqlMembershipProvider" connectionStringName="UmbracoDb" requiresUniqueEmail="true" enablePasswordReset="true" enablePasswordRetrieval="false"/>
<add name="UsersMembershipProvider" applicationName="umbraco4" type="umbraco.providers.UsersMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" />
<add name="ASPPGSqlMembershipProvider" applicationName="umbraco4"
passwordStrengthRegularExpression="" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
forumUpfileFolderPath="D:\www\files"
type="ASPPG.MembershipProviders.ASPPGSqlMembershipProvider, ASPPGSiteIntegrationPackage"/>
</providers>
</membership>
This is how I log in the user:
if (Membership.ValidateUser(txtUserName.Text, txtPasssword.Text)) {
HttpCookie cookie = FormsAuthentication.GetAuthCookie(txtUserName.Text, false);
cookie.Expires = DateTime.Now.AddDays(1);
cookie.Domain = ConfigurationManager.AppSettings["Level2DomainName"];
HttpContext.Current.Response.Cookies.Add(cookie);
Response.Redirect(Request.Url.ToString());
}
When I close the browser, the user is still logged in. How do I make the website forget the user through an option, so the user himself can decide if the website should remember or not?
Thanks in advance :)
M
Have you tried NOT setting the cookie.Expires or at least setting it to DateTime.MinValue for user's that don't want to be 'remembered'?
From MSDN:
Setting the Expires property to MinValue makes this a session Cookie, which is its default value.
Related
I have a register page where the user is assigned to a role as follows once the user clicks on the submit button:
MembershipUser oMU;
if (!(Roles.RoleExists("Stream")))
{
Roles.CreateRole("Stream");
}
oMU = Membership.CreateUser(txtUserName.Text.Trim(), txtPassword.Text.Trim(), txtEmail.Text.Trim());
Membership.UpdateUser(oMU);
Roles.AddUserToRole(oMU.UserName, "Stream");
When the user goes to a login screen, I have the following:
When the user logs in, I need to make sure that they indeed are part of that role:
if (User.IsInRole("Stream"))
{
}
but it never goes into the User.IsInRole block. What do I need to do in order to have the user who registered be part of the Role such that it works with User.IsInRole.
Note that I have a folder as such so I need them to be part of the Streaming Role:
<?xml version="1.0"?>
<configuration>
<system.web>
<authorization>
<deny users="*" />
<allow roles="Stream" />
</authorization>
</system.web>
</configuration>
Move <allow roles="Stream" /> above <deny users="*" />. Otherwise, all users will be denied.
<configuration>
<system.web>
<authorization>
<allow roles="Stream" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
Make sure to you have membership and RoleManager in web.config
Here is the sample -
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<clear/>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="XXXXXSqlConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="XXXXX"/>
</providers>
</membership>
<roleManager enabled="true" cacheRolesInCookie="false" defaultProvider="DefaultRoleProvider">
<providers>
<clear/>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="XXXXXSqlConnection" applicationName="XXXXX"/>
</providers>
</roleManager>
Try using HttpContext to get current login user:
if (HttpContext.Current.User.IsInRole("Stream"))
{
}
When i'm trying to get to Web Site Administration Tool (WAT) (Project->ASP.NET Configuration in Visual Studio) i get following error
You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other >method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in >the root of your site.
And this is my connection string:
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|Database1.mdf;User Instance=true" providerName="System.Data.SqlClient" />
I've also enabled simple membership
<add key="enableSimpleMembership" value="true" />
My roleshipprivider config looks like this
<roleManager enabled="true" defaultProvider="MySqlRoleProvider">
<providers>
<clear />
<add connectionStringName="DefaultConnection" applicationName="/"
name="MySqlRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
And my membership conf
<membership defaultProvider="MyOwnSqlMembershipProvider">
<providers>
<clear/>
<add connectionStringName="DefaultConnection" enablePasswordRetrieval="false"
enablePasswordReset="true" requiresQuestionAndAnswer="false"
requiresUniqueEmail="true" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
name="MyOwnSqlMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
Does anybody know where's the bug?
Thanks in advance, Mateusz Urban
You should add the code below to Global.aspx.cs inside protected void Application_Start() and should appear at the top before any other registrations. This way, it will always be Initialized before an other operations.
if (!WebSecurity.Initialized)
WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"UserProfile", "UserId", "UserName", autoCreateTables: true);
You need to include code to actually initialize the membership provider. The following in _AppStart.cshtml should work:
#{
if (!WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("dbContext", "Users", "Id", "Login", autoCreateTables: false);
}
}
My application has custom Role and MembershipProviders. I've registered them in web.config, but when I try to do if(User.IsInRole("Blah")), neither of my breakpoints in the RoleProvider's Initialize or IsUserInRole are hit. The membership provider works fine, so I guess there must be something I've missed from web.config. This is what I have:
<system.web>
...
<membership defaultProvider="MyAppMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add name="MyAppMembershipProvider"
type="MyAppMembership.MyAppMembershipProvider"
connectionStringName="MyApp"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" writeExceptionsToEventLog="false" />
</providers>
</membership>
<roleManager defaultProvider="MyAppRoleProvider">
<providers>
<clear />
<add name="MyAppRoleProvider"
type="MyAppMembership.MyAppRoleProvider"
connectionStringName="MyApp"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" writeExceptionsToEventLog="false" />
</providers>
</roleManager>
</system.web>
Is there something else which I need?
The attribute enabled of the the <roleManager>-Element defaults to false! Try:
<roleManager enabled="true" defaultProvider="MyAppRoleProvider">
<providers>
<clear />
<add name="MyAppRoleProvider"
type="MyAppMembership.MyAppRoleProvider"
connectionStringName="MyApp"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" writeExceptionsToEventLog="false" />
</providers>
</roleManager>
when i want to use ResetPassword method in vb.net or c# , it can not reset password and make an exeption that say : "The password-answer supplied is wrong".
i think it is caused by hashing system and machine code of hash and salt.
how can i solve this problem ?
add following attribute to your membership cofig section in your Web.Config file.
requiresQuestionAndAnswer="false"
full example
<configuration>
<connectionStrings>
<add name="SqlServices"
connectionString="Data Source=MySqlServer;Integrated Security=SSPI;Initial
Catalog=aspnetdb;" />
</connectionStrings>
<system.web>
<membership
defaultProvider="SqlProvider"
userIsOnlineTimeWindow="20">
<providers>
<remove name="AspNetSqlProvider" />
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="SqlServices"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
passwordFormat="Hashed"
applicationName="/" />
</providers>
</membership>
</system.web>
</configuration>
I used it in a wrong way, and got the same error, hope helps you too. This is my code:
MembershipUser mu = Membership.GetUser(c.Username);
if (mu.PasswordQuestion == c.Question)
{
string pwd = mu.ResetPassword(c.Answer);
mu.ChangePassword(pwd, c.Password);
return RedirectToAction("SignIn");
}
else
{
ViewBag.Message = "Error!";
return View();
}
plz help with one issue.
I have Membership configured with IIS7, tables for it located in my own database, created with aspnet_regsql utility, and I am using custom connection string to access it.
This is part of web.config related to Membership :
<connectionStrings>
<add connectionString="Server=CORESERVER\SQLExpress;Database=Shop;User ID=Tema;Password=Matrix" name="CustomSqlConnection" />
</connectionStrings>
<profile enabled="true">
<providers>
<add name="CustomSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="CustomSqlConnection" />
</providers>
</profile>
<roleManager defaultProvider="AspNetSqlRoleProvider" enabled="true">
<providers>
<add name="CustomSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="CustomSqlConnection" />
</providers>
</roleManager>
<membership defaultProvider="CustomSqlMemberProvider">
<providers>
<add name="CustomSqlMemberProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="CustomSqlConnection" enablePasswordReset="true" enablePasswordRetrieval="false" passwordFormat="Hashed" requiresQuestionAndAnswer="true" requiresUniqueEmail="true" applicationName="/" maxInvalidPasswordAttempts="10" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
</providers>
</membership>
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="login.aspx" name="WebShopAuthentication" protection="All" timeout="30" path="/" requireSSL="false" defaultUrl="~/admin/default.aspx" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
And ... Forms authorization, getting user and his membership info is OK.
But ... getting roles is always FALSE.
MembershipUser userData = Membership.GetUser(HttpContext.Current.User.Identity.Name); // OK !!! IT IS GREAT :)
var a = new RolePrincipal(HttpContext.Current.User.Identity);
var aa = a.getRoles(); // {string[0]} - EMPTY!!!
var b = Roles.IsUserInRole("Administrator", "Administrator"); // FALSE!!!
var c = Roles.Providers["CustomSqlRoleProvider"].GetAllRoles(); // {string[0]} - EMPTY!!!
var d = Roles.IsUserInRole(HttpContext.Current.User.Identity.Name, "Administrator"); // FALSE!!!
var e = HttpContext.Current.User.IsInRole("Administrator"); // FALSE !!!
WHYYYY???
What am i doing wrong???
Just to refine ... authorization works fine and uses roles correctly. Another part of my web.config :
<location path="Admin">
<system.web>
<pages styleSheetTheme="Admin" theme="Admin">
</pages>
<authorization>
<deny users="?" />
<allow roles="Administrator" />
</authorization>
</system.web>
<appSettings>
<add key="ThemeName" value="Admin" />
</appSettings>
</location>
And then in code is used :
Membership.ValidateUser(userName.Text, userPassword.Text) // AND IT WORKS - USER IS LOGGED IN
The answer is that i didn't add applicationName parameter to web.config correctly - after adding i should restart IIS and if needed recreate roles.
This is final version of web.config :
<roleManager defaultProvider="CustomSqlRoleProvider" enabled="true">
<providers>
<add name="CustomSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="CustomSqlConnection" applicationName="/" />
</providers>
</roleManager>