ASP.NET get windows username outside of page - asp.net

I have an Existing ASP.NET reporting application using windows authentication. A lot of the report generation code is in separate classes and has a core error logger that I didn't write, this error logger I believe was built for windows apps as it uses WindowsIdentity.GetCurrent().Name. In the case of ASP.NET I believe this will return the account running the ASP.NET pages at the server.
I believe using User.Identity.Name on the pages would be the correct way to do this but it is not available from within the report generation classes only on the page. Is there a way to obtain it withing the error logger class without passing it as an extra parameter.
There are hundreds of report classes so I dread to have to go through and add a parameter to every one.

If you can use impersonation in your web.config:
....
<authentication mode="Windows"/>
<identity impersonate="true"/>
....
your report classes will get the right user.
If your reporting classes can reference the System.Web assembly and you are willing modify the code, you could also do:
HttpContext.Current.User.Identity.Name
but make sure the caller comes from an ASP.NET request or it will throw a nullref.

Related

Something is seriously wrong with my ASP.NET MVC

I have been programming ASP.NET Web Forms for a long time and recently decided to learn ASP.NET MVC.
However, I am clearly having some issues that I cannot tell how. No one that I have come across in web had the same problems.
#1: Web.config issues
When I first created my MVC project in VS2019, there was no web.config so I added it via project > add new item> Web Configuration File.
All I needed it for was to store my connection string. When added it had only two lines of code:
<configuration>
</configuration>
I added my connection string and the file looked like this:
<configuration>
<connectionStrings>
<add name="connection" connectionString="myconnectionstringblablabla" />
</connectionStrings>
</configuration>
In my controller I tried to fetch the connection string by doing,
string constr = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
And this happened:
Same things happens when fethcing AppSetting keys from web.config.
Is web.config not meant to be used for ASP.NET MVC?
#2 Global.asax
Unlike web.config, Global.asax file doesn't even show up on the add new item menu:
Tried this solution: How to add a Global.asax file to ASP.NET MVC5 project Didnt work either.
#3 Session & HttpContext
In ASP.NET Web.Forms, I would normally use Session variables like this:
Session["ClientID"] = somevalue;
I can't do that in ASP.NET MVC, although I have seen people doing it.
Also I can't access to HttpContext from a non-controller class:
HttpContext.Current.Request.Cookies["mycookie"];
It throws HttpContext does not contain a definition for 'Current'...
====================================
Is Something wrong with my program. I don't know how to check if I am using correct references or assemblies, but I think I am missing something.
Please help

How to enable Windows Authentication for Asp web app?

Windows Authentication seems super simple, but I am still having trouble. So I decided to create a brand new Asp web app project with the Windows Authentication template. Of course, this works. In the designer, <asp:LoginName runat="server" /> works, and in code-behind User.Identity.Name works.
The only setting I can find is in web.config: <authentication mode="Windows"/>.
Back to my own web app project, I verified that I have the same web.config setting. However, the asp.LoginName tag and the User.Identity property have a blank string, i.e., no user name. Also, when using <deny users="?"/>
the page returns a 401.2 Access Denied response.
As I am testing both projects on the same dev machine, both in VS2015, the problem cannot be in settings of IIS Express or VS2015. Also using the same Firefox browser, although I also tried IE.
Is there a project setting in VS2015 that I overlooked?
Update:
I kind of solved this issue by copying all project source files to the brand new Asp web app project. In fact, I was in the process of converting a Web Site project to a Web Application project. I still do not know why I could not get Windows Authentication to work by configuration, but at least I can get going with further development.
However, I am still hoping for an answer . . . :-)
On your Web.config you must add:
<authentication mode="Windows" />
Your server must be a member of AD.
Check:
https://support.microsoft.com/en-us/help/323176/how-to-implement-windows-authentication-and-authorization-in-asp-net
You can write whatever you want in web.config, but if the desired mode of authentication is not enabled in [solution]/.vs/config/applicationhost.config , it will not work. Because the leading dot makes this a hidden path, this config is hard to find. No idea if this is a bug or a feature ...
See also my other question on another test case of this problem: https://stackoverflow.com/a/48806942/1845672

Getting the UserName in MVC3 "internet" application using User.Identity.Name

I've been getting an empty string whenever I try to retrieve the logged in username in my controller. When I first created the app, I selected 'Internet application' template. I also deleted the default account controller, account models and _logon views as I didn't need them. I'm using my own styling, so I removed site.css from the project as well.
After playing around with the web.config for a while, I figured out that "User.Identity.Name" actually works if I change the authentication mode in web.config to windows. If I leave it on 'forms' authentication mode, I only get an empty string whenever I try to get the username.
Recently, I changed the authentication mode to Windows and used User.Identity.Name in one of my controllers to get the user name, but whenever I run the app, I get an error on the browser, stating "localhost/Account/LogOn/..." is not found. (not directing to my usual view) ( I didn't make any changes in Global.asax either.)
If I change the authentication mode back to forms, my view works fine, but I don't get to see the user name (just an empty string). Is there anyway I can find a way around this problem. Is there anything wrong with routing or something ? I can't afford to start over again using "intranet Application" template.
I'm a beginner in MVC, so any help would be greatly appreciated.
Thanks
If you are using asp.net mvc, try System.Environment.UserName
inside your web.config, use
<authentication mode="Windows" />
<identity impersonate="true" />
The error you are getting is because you removed a logon view it still must be refered to somewhere within your application, so if you don't need the logon view, make sure you remove all refences to it from you code.
Internet applications works per default with forms authentication. The purpose of Windows authentication is for intranets, where the web application runs under a windows user. Then the authentication works "automatically".
If you want to have an internet application with registered users, you should put the following configuration in web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
Then you need an AccountController (was there in the default template and you have probably deleted) and a Logon action within the controller. You also need all the views of the account controller (logon, register, change password etc.). The best would be you create a new internet application and check everything that's there. Just copy the stuff you need into your application.
You also need a user database. The default uses an express database with standard tables and stored procedures. If needed, you can use your own tables, then you have to rewrite the methods in the account controller or write your own membership provider.
The reason why you don't see a user name is because you have no login.
EDIT: If you want to display the Windows user name, you should set the authentication mode to windows (or just delete the authentication section, as it is the default). Then you can access the user name. But you will have to delete the tag.
<authentication mode="Windows" />
Sounds like you aren't even authenticating first, so there is no username:
#if (Request.IsAuthenticated) {
<span>#User.Identity.Name</span>
}
else {
<span>You aren't authenticated</span>
}

MVC4 ExtendedMembershipProvider and entityframework

i want to be able to use the same database for the application as the asp membership details for forms authentication. I am currently using MVC4. When i started and added the system.web.providers to my project i got a seperate default connection. I have modified the string to point to the same database as that being used in my application (entityframework).
Should i expect the providers to autocreate the tables in this database i.e.
webpages_Membership
UserProfile
webpages_Roles
webpages_OAuthMembership
Currently I am getting...
To call this method, the "Membership.Provider" property must be an
instance of "ExtendedMembershipProvider"
when i try and register a new user via the default mvc4 application template. And the tables are absent.
regards
Tim
the issue here is that the default mvc4 internet template is using simplemembership to manage membership/roles information. the code in the template has assumption of this and can only work with simplemembership. when you install universal providers the account controller code blows up since it cannot understand universal providers. look at this post which explains further on this scenario
http://weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx
I have the same issue,
however mine isn't solved, but many people say add this to your web.config
<add key="enableSimpleMembership" value="false"/>
<add key="autoFormsAuthentication" value="false"/>
and if that doesn't work try making the top one true as well.

Configure ASP.NET application to use two authentication methods?

I am new to ASP.NET development and moreover I am only extending an existing application which i did not create.
I have a working ASP.NET application which uses "Forms authentication" throughout all its pages. I have added a new webservice in a subfolder "webservices\Dummy.asmx". This webservice works fine but because it should be called by an external application which can't authenticate through a form, i need to enable "Integrated Windows Authentication (Basic Authentication or Digest Authentication)" ONLY for the subfolder "webservices".
I tried to configure it in IIS but it did not work.
So that i can set a different authentication method i have to create the folder "webservices" as an "Application". But if i do so then my function stops working with the error "Could not create type 'Dummy'."
Is it possible to have one web application and to authentication methods ?
If yes how is it configured in IIS ?
Or what would be the better way if i need ONLY one page (webservice) to use a different authentication then the rest of my application.
Thank you in advance for any information.
Bye
PS: I use Windows 2008 Server and the app runs on .NET Framwork 2.0
I tried to configure it in IIS but it
did not work. So that i can set a
different authentication method i have
to create the folder "webservices" as
an "Application". But if i do so then
my function stops working with the
error "Could not create type 'Dummy'."
This is the correct way. Can you explain the problem you are having here ? What is dummy ?
Mixing Forms and Windows Security in
ASP.NET
http://msdn.microsoft.com/en-us/library/ms972958.aspx
Web services that live in a larger application often do not need to be protected. If that's acceptable in your scenario, you can use a standard web.config construct to allow anonymous access to the service while still protecting the rest of the application.
Add a location node to the main configuration node that defines the rules for just the web service:
<location path="webservices\Dummy.asmx">
<system.web>
<authorization>
<!-- this overrides the parent app protection rules -->
<allow users="*" />
</authorization>
</system.web>
</location>

Resources