Request.ServerVariables("LOGON USER") returns empty - iis

Web.config file
<authentication mode="Windows" />
<authorization>
<allow users ="*" />
</authorization>
IIS permissions
(Unchecked)Enable ananymouse access
(Checked)Integrated windows authentication
C# code,
welcomeUser.InnerText = Request.ServerVariables.Get("LOGON USER");
What am I missing to be able to display Windows User ID ?

I think the variable is LOGON_USER isn't it? (With underscore) See here
You may find that this gives you IUSR_MachineName though, so you might want to look up better ways of finding the actual logged in user, such as User.Identity.Name or by using WindowsIdentity.GetCurrent().Name;

Related

ELMAH - Get SMTP credentials from Azure Application Settings

I've got an Azure Web App using ELMAH to log unhandled exceptions.
When I first deployed it, the web.config had the full SMTP setup defined in it, and ELMAH emailed exceptions:
<system.net>
<mailSettings>
<smtp from="me#mydomain.com">
<network host="smtp.mailprovider.com"
port="123"
userName="myUserName"
password="p#ssw0rd" />
</stmp>
</mailSettings>
</system.net>
The username and password have since been removed from the web.config, and they're now stored as application settings, configured through the Azure Portal.
Most of the emails I send still work fine, as the email code can access these application settings and use them when instantiating the SmtpClient, e.g.:
var userName = WebConfigurationManager.AppSettings["smtp.userName"];
var password = WebConfigurationManager.AppSettings["smtp.password"];
var credentials = new NetworkCredential(userName, password);
using (var smtpClient = new SmtpClient { Credentials = credentials })
{
await smtpClient.SendMailAsync(mailMessage);
}
What's the best way to get ELMAH to use the credentials stored in the application settings?
Options I can see:
There is a page on the wiki explaining how to use ELMAH's ErrorTweetModule to do an HTTP form post with the error details to any URL. The controller receiving the post could then use the stored credentials to email the details on.
The WebBase has a link to an article suggesting you can send emails directly to the recipient's SMTP server without authentication, but it says this may not work if you have DomainKeys set up, which I do.
This answer links to an article about intercepting the Mailing event, to customise the message.
I ended up creating a custom version of Elmah's ErrorMailModule, derived from the standard one, but overriding the SendMail method, based on some advice from Atif Aziz in a discussion on Google Groups.
The only changes required were to create the new module, and switch the Web.Config to use the custom module instead of the standard one.
Module
using System;
using System.Net.Mail;
namespace Test
{
public class ErrorMailModule : Elmah.ErrorMailModule
{
protected override void SendMail(MailMessage mail)
{
if (mail == null) throw new ArgumentNullException(nameof(mail));
// do what you want with the mail
// (in my case this fires up the email service, which
// gets the credentials from the Azure settings)
}
}
}
Web Config Changes
All that's required is to change the two occurrences of Elmah.ErrorLogModule, Elmah to your own module, in this case Test.ErrorMailModule.
So, instead of this...
<system.web>
<httpModules>
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
</httpModules>
</system.web>
<system.webServer>
<modules>
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
</modules>
</system.webServer>
...you should now have this:
<system.web>
<httpModules>
<add name="ErrorMail" type="Test.ErrorMailModule" />
</httpModules>
</system.web>
<system.webServer>
<modules>
<add name="ErrorMail" type="Test.ErrorMailModule" preCondition="managedHandler" />
</modules>
</system.webServer>
You will still need the errorMail section, as Elmah is still responsible for creating the email. Mine looks like this:
<elmah>
<errorMail from="user#domain.com" to="user#domain.com" subject="Custom Email Module"/>
</elmah>
Creating a HTTP request could work, but that should be the solution if everything else doesn't work IMO. Intercepting the Mailing event doesn't work, since you do not have access to the SmtpClient with the credentials in that event.
I've looked at different ways to update the SMTP settings from code. At first I though that I could just get a reference to the smtp section and update the properties, since they all have setter. But the code throw a configuration exception on runtime.
From what I can find, the only way to update the username and password in smtp section, is to read the web.config, update it and write the new version. Here's an example of writing updates to web.config:
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = configuration.GetSection("system.net/mailSettings/smtp") as SmtpSection;
section.Network.UserName = ConfigurationManager.AppSettings["myusername"];
section.Network.Password = ConfigurationManager.AppSettings["mypassword"];
configuration.Save();
The code actually updates the web.config. The code can be run at startup, but that would modify your web.config file locally as well. Another approach would be to run the code as part of a post deployment task with Azure.

Turn off / Disable windows authentication for asp.net-mvc

I created a new asp.net-mvc project and during setup I chose to use Windows Authentication.
Now I like to turn it off(at least for a while).
I changed the web.config to this
<authentication mode="None" />
But that does change anything. It will still prompt me. I am using the IIS Express.
UPDATE: I mean it still prompts me when using Firefox. Internet Explorer will continue and not show my domain username
1.) Close VS
2.) Remove the .vs/config or the .vs folder next to your solution. The IIS Express regenerates the config/applicationhost.config file. Changing this file does NOT help - it is regenerated
3.) Edit the <project>.csproj.user file. There change the lines
<IISExpressAnonymousAuthentication>disabled</IISExpressAnonymousAuthentication>
<IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>
to
<IISExpressAnonymousAuthentication>enabled</IISExpressAnonymousAuthentication>
<IISExpressWindowsAuthentication>disabled</IISExpressWindowsAuthentication>
4.) Edit and change the web.config
Change
<authentication mode="Windows" />
to
<authentication mode="None" />
or comment the whole authentication XML element.
The web config should overwrite the IIS express config but in this case it seems it does not. What you can try to do is to turn it off on the IIS level as well.
You can go to this directory \IISExpress\config\applicationhost.config open up this file and set the <windowsAuthentication enabled="false" />.
I found this was possible in the web config by using the following documentation:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-3.1&tabs=visual-studio
The relevant bloc of web.config is:
<security>
<authentication>
<windowsAuthentication enabled="false" />
</authentication>
</security>
You should unload the project, edit the project .csproj file and change the lines:
<IISExpressAnonymousAuthentication>disabled</IISExpressAnonymousAuthentication>
<IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>
Then, you should delete the .csproj.user file for your project, and remove de .vs directory for your solution.

System D-Bus does not allow punching out ownership with conf files

I am trying to create a daemon service that runs on the system bus where the permissions for sending and receiving from this service should be completely open to anybody. (Security is not a concern for this service). When I attempt to register the service using QtDbus (using the PyQt for it) I get this error: Connection ":1.0" is not allowed to own the service "org.dbus.arduino" due to security policies in the configuration file. This other stack overflow has the same error, but does not help at all in this situation for some reason. dbus_bus_request_name (): Connections are not allowed to own the service.
Normally you're supposed to leave the system.conf file in-tact and add your permissions "punch out" config file in the system.d directory. I have done this, but it does not seem to change anything, regardless with how open I make the permissions. In fact I'm almost positive it's not changing anything! Here is my conf file as it sits right this moment.
<!DOCTYPE busconfig PUBLIC
"-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<policy user="myUser">
<allow own="*"/>
<allow own="org.dbus.arduino"/>
<allow send_type="method_call" log="true"/>
</policy>
<policy user="root">
<allow own="*"/>
<allow own="org.dbus.arduino"/>
<allow send_type="method_call" log="true"/>
</policy>
<policy context="default">
</policy>
</busconfig>
Even if I do this or things like it, it STILL doesn't work.
<busconfig>
<policy context="default">
<allow own="*"/>
<allow own="org.dbus.arduino"/>
<allow send_type="method_call" log="true"/>
</policy>
</busconfig>
I even put the name of the file starting with a z so that it may be the very last one that is read in. Here is the system.conf file, note where I have commented out the "allow own" section. This is the ONLY way to get this to work (and the worst possible "fix").
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<!-- Our well-known bus type, do not change this -->
<type>system</type>
<!-- Run as special user -->
<user>messagebus</user>
<!-- Fork into daemon mode -->
<fork/>
<!-- We use system service launching using a helper -->
<standard_system_servicedirs/>
<!-- This is a setuid helper that is used to launch system services -->
<servicehelper>/lib/dbus-1/dbus-daemon-launch-helper</servicehelper>
<!-- Write a pid file -->
<pidfile>/var/run/dbus/pid</pidfile>
<!-- Enable logging to syslog -->
<syslog/>
<!-- Only allow socket-credentials-based authentication -->
<auth>EXTERNAL</auth>
<!-- Only listen on a local socket. (abstract=/path/to/socket
means use abstract namespace, don't really create filesystem
file; only Linux supports this. Use path=/whatever on other
systems.) -->
<listen>unix:path=/var/run/dbus/system_bus_socket</listen>
<policy context="default">
<!-- All users can connect to system bus -->
<allow user="*"/>
<!-- Holes must be punched in service configuration files for
name ownership and sending method calls -->
<deny own="*"/>
<deny send_type="method_call" log="true"/>
<!-- THIS IS THE ONLY WAY TO GET THIS TO WORK
<allow own="*"/>
<allow send_type="method_call" log="true"/>
-->
<!-- Signals and reply messages (method returns, errors) are allowed
by default -->
<allow send_type="signal"/>
<allow send_requested_reply="true" send_type="method_return"/>
<allow send_requested_reply="true" send_type="error"/>
<!-- All messages may be received by default -->
<allow receive_type="method_call"/>
<allow receive_type="method_return"/>
<allow receive_type="error"/>
<allow receive_type="signal"/>
<!-- Allow anyone to talk to the message bus -->
<allow send_destination="org.freedesktop.DBus"/>
<!-- But disallow some specific bus services -->
<deny send_destination="org.freedesktop.DBus"
send_interface="org.freedesktop.DBus"
send_member="UpdateActivationEnvironment"/>
</policy>
<!-- Config files are placed here that among other things, punch
holes in the above policy for specific services. -->
<includedir>system.d</includedir>
<!-- This is included last so local configuration can override what's
in this standard file -->
<include ignore_missing="yes">system-local.conf</include>
<include if_selinux_enabled="yes" selinux_root_relative="yes">contexts/dbus_contexts</include>
</busconfig>
I absolutely have to use the System bus because I am deploying it on a Raspberry Pi without a GUI, (no x11, and no session bus). I was able to get the Raspberry Pi working only by completely allowing everything on the system bus (security is not nearly as big of a deal on this device). Obviously, there is no way I'm allowing that to occur on my development machine. As background I am using Opensuse 12.2 and the Raspberry Pi is Debian Squeeze. I cannot own the service with my user account, nor root, unless I completely open the permissions up, in that case it works just fine. I will also note that when I completely opened up the system bus, I still had to use root to send messages to the daemon (a terminate command). I'd like the solution to be able to be runnable via a particular user with root having access as well. I am also OK with the solution only allowing the same user and root to send messages to it.
Thanks for any help I'm sure it's a small issue!
I finally found the issue. When Dbus looks for configuration files for punching out permissions (like ownerships) the file not only must be in system.d/ but it must also end in .conf.
My configuration file "org.dbus.arduino" should have been "org.dbus.arduino.conf". I removed the code from system.conf. Confirmed I no longer had permissions, created a configuration file at "system.d/org.dbus.arduino.conf", I was granted permissions. I then attempted to rename the file to just "org.dbus.arduino" and confirmed the permissions were denied.
I did the same solution as the accepted answer but I also got it to work with this alternative.
I noticed that in my system.conf file, there is this note:
For local configuration changes, create a file system-local.conf or
files matching system.d/*.conf in the same directory as this one, with
a element containing configuration directives. These
directives can override D-Bus or OS defaults.
Instead of putting a <name.of.my.dbus.service>.conf under system.d/, I was able to make it work by creating a system-local.conf in the same directory as the system.conf, with the contents like this:
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<policy context="default">
<allow own="dbus.my.own.service"/>
</policy>
</busconfig>

PUT + DELETE Http Verbs returning 401/405 from API on shared hosting webserver

I have created an MVC Web Api for some university coursework, that works as expected on my development machine (Running VS11).
However when I deploy the application to the webserver on 123reg HttpVerbs other than GET and POST appear to not reach my application at all, initially a 401 Not Authorised response was returned; however after turning off the "WebDAV" module as suggested here these 401s became 405 Method not allowed. In this case I only disabled the handlers as disabling both the handlers and the module meant that my application did not start at all (Error 500 without a stacktrace [custom errors are off]).
I am planning to utilise the forms membership provider to add authentication capabilities to my API, however I removed any [Authorise] attributes from my code when 401s began appearing.
Applications on 123Reg's shared hosting are run under Medium trust.
I have been in contact with 123Reg support, and they have been semi helpful, but have since decided that they cannot help me further (They suggested adding HttpHandlers as detailed below) (Apparently, I should consult a web designer...)
Things I have tried:
I have added [AllowAnonymous] Attributes to my controllers and/or actions with no effect.
I have added the authorization web.config attribute allowing all verbs and paths to all users both authenticated and not:
<authorization>
<allow users="*" />
<allow users="?" />
<allow verbs="*" users="*" />
<allow verbs="*" users="?" />
</authorization>
I have added (As suggested by 123Reg):
<system.webServer>
<handlers>
<remove name="WebDAV" />
<add name="PUTVerbHandler" path="*" verb="PUT" modules="ProtocolSupportModule" resourceType="Unspecified" />
<add name="DELETEVerbHandler" path="*" verb="DELETE" modules="ProtocolSupportModule" resourceType="Unspecified" />
</handlers>
</system.webServer>
This appeared to be a step forward, as we now receive 405 responses rather then 401 respones, however I am now unable to make any further progress. Additionally I have also added:
<httpHandlers>
<add verb="*" path="*" type="System.Web.Mvc.MvcHttpHandler"/>
</httpHandlers>
This also made no difference.
Any help you can give would be much appreciated (I dont really want to have to move host for this application!)
This post solved my problem. I did all the regular things: added all the necessary <handlers> entries, disabled WebDAV, but I still had 401.3 Unauthorized.
Enabling forms authentication solved the problem:
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms" />
</system.web>
I found this: http://forums.iis.net/t/1163441.aspx
From the looks of that forum post, you need to completely uninstall WebDAV for the PUT and DELETE Verbs to work. This is not going to help on a shared webhosting scenario unfortunately.
For me it was something different.
I had to go to the site folder, open the security tab for the folder, press Edit button to change group or user names permissions, find the site from my IIS 8 sites and give it a full control permission.

authenticate file in _layouts folder

I have a public facing website www.abcd.com .. I have added a file "Authenticated.html" in _layouts folder of it. so now when user is going to this url
www.abcd.com/_layouts/authenitcated.html ... one can see all the content in it. I want this particular file to be only shown to authenticated users and asks for authentication. If there is any way i can achieve this?
Here is a couple of alternatives:
Put the following into _layouts/web.config:
<location path="Authenticated.html">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
Or as I'd prefer change your extension from html to aspx and put these two lines at the top:
<%# Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%#page Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" %>
Alrite I figure it out...go to IIS select the web application you want...go to the file in _layouts folder you want to authenticate ->properties->File Security->uncheck anonymous access...

Resources