MachineKey change does not reflect in web.config - c#

In my web application, there is an administrator ability to change the validation method/algorithm to SHA1 to HMACSHA256, HMACSHA384, etc. etc.
In the code, when I retrieve the value from the web.config using ConfigurationManager, it shows as being updated.
However, when I open up the Web.config itself, the value does not appear in the MachineKey section. Why is it now showing up?
edit: The technloogy I am using is Visual Studio C# and MVC. A portion of the web.config is below:
<system.web>
<machineKey validationKey="22FEA7D6533FCCE331C2342A1801051F5E2890749CB2D5EF2EEABF8B0D944F389F46FA061D1A203EB75F3A9197914299676917FFD355456CFA0B49CA4C30B348"
decryptionKey="30B2FA2A8C54665E18D9A35E3541BFED6A3E8A640DBA4070" />
<authentication mode="Forms">
<forms name="FormsAuth1" loginUrl="https://localhost/OidcApplication/Oidc/Authenticate" timeout="2880" requireSSL="false" />
</authentication>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
This is how I retrieve the machine key values:
machineKeyConfig = (MachineKeySection)GetConfigurationSection("system.web/machineKey");
And this is how I set the machine key values:
var machineKeyConfig = (MachineKeySection)GetConfigurationSection("system.web/machineKey");
machineKeyConfig.DecryptionKey = machineKeySettings.DecryptionKey;
machineKeyConfig.Validation = machineKeySettings.Validation;
machineKeyConfig.ValidationKey = machineKeySettings.ValidationKey;
machineKeyConfig.CurrentConfiguration.Save(ConfigurationSaveMode.Minimal);

First of all, I would check whether the file you are saving to is the same you are reading:
var ConfigFilePath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
By the way, what's the class and namespace of the GetConfigurationSection method?

Related

Force user change password after first login asp.net mvc with Forms authentication

I'm have a mvc app that use with form authentication security client and all the manage user's is made in server side with wcf protocol.
and in the server site I'm saving the user tocken in the sessoin
string token = Srv.ValidateUser(out isNewUser, model.UserName, model.Password, model.IdentityNumber);
if (!string.IsNullOrEmpty(token))
{
Session["Token"] = token;
}
with this token I Identifies in the services
and the user name in the form authentication
FormsAuthentication.SetAuthCookie(model.UserName, false);
and now I dont know how to force user change password after first login or after password expired.
My config is:
<system.web>
<sessionState mode="InProc" cookieless="true" timeout="20" />
<authentication mode="Forms">
<forms path="/" loginUrl="~/Account/Login" />
</authentication>
<authorization>
<allow users="*" />
<deny users="?" />
</authorization>
<identity impersonate="true" />
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
Can anyone help me?
In your Login post action, you can check LastPasswordChangedDate like so:
var currentUser = Membership.GetUser(model.Email);
if (currentUser != null)
{
if (currentUser.LastPasswordChangedDate == currentUser.CreationDate)
{
// User has not changed password since created.
return RedirectPermanent("Login/?userName=" + model.Email);
}
}

Roles not working in ActiveDirectoryMembershipProvider

I have a web-site which uses forms auth and ActiveDirectoryMembershipProvider. I have an Action in controller like this:
[Authorize(Roles = "jira-developers")]
[HttpGet]
public ActionResult MonitorForm()
{
var list = Dal.GetActualData();
return View(list);
}
I'm totally sure that my user is in group with Name="jira-developers", but auth fails. If i remove Roles parameter, the auth will work fine.
What am i doing wrong? I'll be gratefull for any help!
As nobody gave me an answer i'll answer this question myself. ActiveDirectoryMembershipProvider can only handle auth and to enable roles management i had to specify rolesManager. I implemented my own RoleProvider (because i need some specific functionality) and now my Web.Config looks like this:
<system.web>
<authentication mode="Forms">
<forms name=".ADAuthCookie" loginUrl="~/Account/Login" timeout="45" slidingExpiration="false" protection="All" />
</authentication>
<membership defaultProvider="ADMembershipProvider">
<providers>
<clear />
<add name="ADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider"
connectionStringName="ADConnectionString"
attributeMapUsername="sAMAccountName" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="AdRoleProvider">
<providers>
<clear/>
<add name="AdRoleProvider" type="InternalAutomation.Providers.AdRoleProvider"/>
</providers>
</roleManager>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
Do you have the role defined in your Roles table? (Depending on the version you're using the table could be named slightly different than my screen shot below)
You should have an entry with a 'RoleName' of "jira-developers".
The user hitting the action should also have an entry in the '...UsersInRoles' table.

Increasing maxRequestLength in ServiceStack for specific route

So I recently wrote a simple service to upload files to my server. Everything works fine. My web.config looks like this (max upload size is restricted to 20 MB):
<configuration>
<system.web>
<httpRuntime maxRequestLength="20480" executionTimeout="600" />
<httpHandlers>
<add path="api*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
</httpHandlers>
...
</system.web>
</configuration>
All my routes begin with /api/, for example my upload service is at /api/documents/upload.
Now my question is: Is it possible to define different upload sizes for different services? (in my example every service is limited to 20 MB!)
I tried some stuff with the location-tag but it didn't worked with the httpRuntime-tag. Anyone tried something like this already?
Use the location element, it should work (Check the path without ~/)
<configuration>
<location path="api/documents/upload">
<system.web>
<httpRuntime maxRequestLength="20480" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="20971520" />
</requestFiltering>
</security>
</system.webServer>
</location>
</configuration>

Session Expire in MVC

I am facing a problem,
I have set session time out in web.config
<system.web>
<sessionState timeout="60" mode="InProc" />
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
</system.web>
In my controller
public ActionResult CreateBrand()
{
Session.Timeout=60;
Purchase purchase = Session["purchaseItem"] as Purchase;
if (purchase!=null && purchase.Brand != null)
{
return View(purchase.Brand);
}
return View();
}
You never actually ask a question, so I'll take a stab at guessing what you're asking...
<sessionState timeout="60" mode="InProc" />
When mode="InProc", setting timeout="60" usually does not extend the session timeout beyond 20 minutes because the application pool will spin down (by default) after 20 minutes.
No application pool = no process = no session.
Either change your application pool settings or use a different session state provider.

Issues with custom ASP.NET RoleProvider

I am having difficulties implementing a custom ASP.NET RoleProvider.
First off, let me show you the relevant settings in my web.config file:
<?xml version="1.0"?>
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
name="FormsAuthentication"
path="Default.aspx"
timeout="20"/>
</authentication>
<membership defaultProvider="MembershipProvider">
<providers>
<clear />
<add name="MembershipProvider"
type="CompanyName.Security.MembershipProvider" />
</providers>
</membership>
<roleManager defaultProvider="RoleProvider"
enabled="true">
<providers>
<clear />
<add name="RoleProvider"
type="CompanyName.Security.RoleProvider" />
</providers>
</roleManager>
</system.web>
<location path="Employees.aspx">
<system.web>
<authorization>
<deny users="?"/>
<allow roles="Employees"/>
</authorization>
</system.web>
</location>
</configuration>
Here's the code for the login button's event handler:
if (Membership.ValidateUser(tbxUsername.Text, tbxPassword.Text))
Response.Redirect("./Employees.aspx");
else
{
tbxUsername.Text = string.Empty;
tbxPassword.Text = string.Empty;
tbxUsername.Focus();
lblLogin.Visible = true;
}
Side Note based on FormsAuthentication.RedirectFromLoginPage() suggestion:
[It has been suggested that I use FormsAuthentication.RedirectFromLoginPage() instead of Response.Redirect(). Eventually, I'd like to redirect the user to a different page based on his/her role. I don't know how FormsAuthentication.RedirectFromLoginPage() would allow me to do this as it does not accept a redirection url as a parameter. In addition, it is my understanding that I could call FormsAuthentication.SetAuthCookie() prior to Response.Redirect() in order to create the authentication cookie that FormsAuthentication.RedirectFromLoginPage() creates. Please let me know if my thought process here is wrong.]
After stepping through the source, I can see that Membership.ValidateUser() is executing the ValidateUser() function of my custom MembershipProvider class. However, when a valid user logs in, and is redirected to Employees.aspx, the user is returned to Login.aspx**?ReturnUrl=%2fEmployees.aspx**. I assume that this is because although the user authenticates, s/he is failing authorization to the Employees.aspx resource.
With that assumption, I created breakpoints on every function in my custom RoleProvider class to see where things run amuck. Not one of them breaks execution when I debug. Most of the code in my RoleProvider throws NotYetImplementetExceptions, but I would still expect to hit the breakpoints (and would then implement those required functions). Here are two dumbed-down functions I have implemented:
public override string[] GetRolesForUser(string username)
{
return new string[1] {"Employees"};
}
public override bool IsUserInRole(string username, string roleName)
{
return true;
}
I assume that since the RoleProvider code never executes, that something must be wrong with my web.config.
I've searched for an answer to this for the past two days and have tried various changes without success. Does anyone see where I'm going wrong?
Thanks in advance!
After authenticating the user using Membership.ValidateUser, you should call FormsAuthentication.RedirectFromLoginPage rather than Response.Redirect to create the forms authentication ticket.
See the MSDN documentation for Membership.ValidateUser for an example.
EDIT
Or if you want to redirect to a specific page, call FormsAuthentication.SetAuthCookie to create the forms authentication ticket before calling Response.Redirect.
It redirects authenticated users to default.aspx
Actually it redirects back to the page that was originally requested, which is not necessarily default.aspx
EDIT 2
Also there is a problem with your configuration:
The path attribute should not point to a specific page (Default.aspx in your case), but the root directory of the site. The default is "/" because most browsers are case-sensitive and so won't send the cookie if there is a case mismatch.
<forms loginUrl="Login.aspx"
name="FormsAuthentication"
path="/"
timeout="20"/>
Check if user is in role:
If (Roles.IsUserInRole("Employees"))
{
}
or try if it works without role checking:
<allow users="*"/>
maybe helps configuration change:
<location path="Employees.aspx">
<system.web>
<authorization>
<allow roles="Employees"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
I changed the path value (see below) from "Default.aspx" to "/" and now the breakpoints in the custom RoleProvider are being hit!
Does not work:
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
name="FormsAuthentication"
path="Default.aspx"
timeout="20"/>
</authentication>
Works:
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
name="FormsAuthentication"
path="/"
timeout="20"/>
</authentication>

Categories

Resources