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

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>
}

Related

Get currently logged in user asp.net

I´m having a bit of trouble and I would like to see if you all could help me out!
For my WebApp in ASP.net, I need to be able to get the user name.
I had been able to do it through:
user = Principal.WindowsIdentity.GetCurrent.Name.ToString on my developement machine, but when i go to production, it shows ASP.net as user...
I also tried with
user = Context.User.Identity.Name.ToString
and in dev station i get a blank string, and in production, I get "AppPool/ASP.net4.0
Any Ideas as to how i could get this working?
This WebApp is supposed to work in the Intranet.
make sure that you've enabled Windows Authentication in your web.config (check your .config.xxx transforms too). You should see this tag in your web.config:
<system.web>
...
<authentication mode="Windows" />
...
</system.web>

ASP.NET 4.0 Single sign on betwen parent website and child web-application fails

I've got the following structure
www.website.com --> ASP.NET 4.0 Web-site
www.website.com/blog --> NET 4.0, Web-Application
Both do form-authentication against the same SQL database and use the framework ASP.NET memberships and roles. I can log into each portion just fine (same user/password) but the authentication doesn't carry over i.e. if I log into / and then click a link to /blog/, /blog/ thinks I'm Anonymous and prompts for login again. I've done the basics
i.e.
Identical <authentication mode="Forms"> in both the site as well as app web.configs
Identical <machineKey> section (yes, identical validationKey and decryptionKey)
So I then inspected the cookies generated and noticed that website and the web application seem to be working on different cookies.
Cookies created by website.com/blog
.ASPXFORMSAUTH-27604f05-86ad-47ef-9e05-950bb762570c
.ASPXROLES
Cookies created by website.com
.ASPXFORMSAUTH
I think this is the problem, although I see it despite having identical <authentication> sections which looks like
<authentication mode="Forms">
<forms timeout="30" slidingExpiration="true" name=".ASPXFORMSAUTH" enableCrossAppRedirects="true" protection="All" cookieless="UseCookies"/>
</authentication>
I did read several other posts like
Single Sign On with Forms Authentication
as well as
http://msdn.microsoft.com/en-us/library/eb0zx8fc.aspx
There were also a few other posts I can't recall now. I've gone through them (all?) but am still stuck. I can gladly supply more debug data if needed.
Would really appreciate any tips someone might have! I think I'm hitting a wall on this one!
Ok, so I was able to answer my own question after beating around it for longer.
Basically, BlogEngine.NET 2.5 (my web-app) seems to be overriding the .NET 4.0 framework way of doing things. There are a couple of things you need to fix, all within BlogEngine.Core\Security\Security.cs (download the BlogEngine.NET source code)
Part 1: Fix cookie name
In there is a method FormsAuthCookieName which I changed as follows:
File: BlogEngine.Core\Security\Security.cs
Method: FormsAuthCookieName()
// return FormsAuthentication.FormsCookieName + "-" + Blog.CurrentInstance.Id.ToString();
return FormsAuthentication.FormsCookieName;
This ensures that the cookie names are the same. One hurdle down ...
Part 2: Avoid web-app/BlogEngine.NET's login page/controls/code
Instead of directing users log into the BlogEngine.Net's login.aspx (www.website.com\blog\account\login.aspx), I pointed all login links to my main website's login.aspx page (www.website.com\login.aspx). In case you're wondering how to implement you own site-wide authentication, this is a super-quick guide
msdn.microsoft.com/en-us/library/ff184050.aspx.
I also had to add something like this to both the website web.config as well as the web-app web.config, so anytime a protected resource is accessed (from website or web app) my own global /login/aspx is used.
<authentication mode="Forms">
<forms timeout="30" loginUrl="/login.aspx" blah blah />
</authentication>
Now, my own generic, site-wide user login controls will be creating the (.NET framework standard) authentication cookies and the (user) role cookies. By avoiding the BlogEngine.NET's login.aspx we're cleaner plus we avoid calling this code which is problematic.
File: BlogEngine.Core\Security\Security.cs
Method: AuthenticateUser(string username, string password, bool rememberMe)
Details:That code adds a "blog instance" into the cookie, so so if you have multiple blogs on the same domain, this prevents user1 authenticated on blog instance 1 from NOT being automatically authenticated on blog instance 2. I'm guessing most will only have one blog per domain (www.domain.com\blog!), so this is unnecessary. More importantly, that check breaks our single sign-on.
Two hurdles down ...
Part 3: Fix Per-access authorization check
Now, our site wide, standardized login.aspx doesn't add the specific BlogEngine.NET instance ID (see above). This would have been ok, except that there is still some BlogEngine.NET code that specifically looks for that. We don't need that check either, so lets remove that offending check...
File: BlogEngine.Core\Security\Security.cs
Method: void Init(HttpApplication context)
// Comment line below to revert to only-framework/default processing
//context.AuthenticateRequest += ContextAuthenticateRequest;
So at this point you should have
All logins handled by a single, site wide login.aspx
All authentication cookies and user role cookies created by the above site wide login.aspx
All such cookies encrypted and protected per of both the website & web-app web.configs (which should match!)
Which in turn allows single sign on :) !! Hooray !
In addition: in both web.configs you must insert machinekey with the same validationKey and the same decryptionKey.

Help with Login Page in vb.net

Im new to .NET and have been searching on this issue but no luck. I have created a login page, with a user Id and password. In my webconfig, I put the following code in to deny users who are not authenicated.
<authentication mode="Forms">
<forms loginUrl="Login.aspx" timeout="10" protection="All" />
</authentication>
<authorization>
<deny users="?"></deny>
</authorization>
What im trying to accomplish is that when a user enters the correct information, I would like to store information small information about the user in a cookie, say for example if there an admin, manager, user, etc...Here is the code that occurs when the user click the submit button. The problem is that the page doesnt redirect to the page after user enter correct information. Any help would be very much appreciated.
If txtPassword.Text.ToLower = "test" Then
'Create a cookie
Dim cookie As New HttpCookie("UserInfo")
'Cookie variables
cookie("User") = txtUser.Text
cookie("UserGroup") = "Admin"
'Add Cookies to current web responses
Response.Cookies.Add(cookie)
Response.Redirect("login_successful.aspx")
'FormsAuthentication.RedirectToLoginPage("login_successful.aspx")
Else
lblResult.Text = "Incorrect Password"
End If
I wouldn't recommend using cookies to store role information. Use one of the built in providers to accomplish this task. For example, try this.
Open Visual Studio or Visual Studio Express and create a new "ASP.NET Web Application." You will notice that it includes an "Account" directory with examples of how to use the built in providers. You have to set up the database with the correct tables, roles, sprocs, etc to use the built in providers but it's easy. If you have .NET 4.0 installed the program that sets up the database to use the built in providers it called aspnet_regsql.exe and it's typically located here:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_regsql.exe
Then to solve your login problem you can use the Login control and use the Login.DestinationPageUrl attribute to redirect the user to which ever page you desire after it logs in.
Even if you don't use the built in providers this will give you a much better idea of how to go about implementing roles into your webpage.
I guess before redirecting you have to set authentication cookie first by calling FormsAuthentication.SetAuthCookie method.
And yes do consider the comment regarding cookies of joel coehoorn about saving information.
Rather than using a cookie to store that information (which can be hacked), you should store Roles in the ASPNetRoles table and associate roles to users when they are created. You can check a role with the following code:
If (Roles.IsUserInRole("rolename")) Then
'Do something useful
End If
As for the redirect, in what event handler is it included?
Can you try these two?
1) The webconfig may need refrence to the cookie name
<forms name="UserInfo" ...
2) Webconfig could also require being told who to allow
<authorzation>
<allow user="Admin" />
<deny...

ASP.NET MVC - Action with parameter is redirecting to login page which shouldn't be

I have a simple action that takes a single paramter as a string, it returns a users profile page which is working fine.
However a user has told me today that nobody can see he's profile unless logged in, it simply redirects to the login page.
I have checked the IIS7 log file, and I can see that it is returning a 302 status and then loads the login page.
Here is the page that doesn't work:
http://www.house-mixes.com/profile/mixchemist/
Here is an example that works fine:
http://www.house-mixes.com/profile/housemixes/
There are no authorize attributes on the action / controller, I do have Helicon Ape installed managing some custom redirects for me, but I have disabled this and still get the same result.
I'm pretty puzzled here at what could cause this only on a certain profile, any ideas?
EDIT:
There is definetly no Authorize attributes at any level, default or custom. My web.config is pretty standard, and I am using MVC2:
<authentication mode="Forms">
<forms cookieless="UseCookies" enableCrossAppRedirects="true" loginUrl="~/Login" name=".ASPXAUTH" slidingExpiration="true" timeout="100000" requireSSL="false" />
</authentication>
Here is my controllers action (only attribute at controller level is [HandleError]):
[Transaction]
[PassParametersDuringRedirect]
[ModelStateToTempData]
[HttpGet]
public ActionResult Index(string artist)
{
Account account = accountTasks.GetProfileByUsername(artist);
if (account == null)
return RedirectToAction<HomeController>(x => x.Index(), null);
var viewModel = Mapper.Map<Account, ProfilePageViewModel>(account);
return View(viewModel);
}
Paul
That definitely looks like an action that requires authentication. No idea where the problem comes from as you haven't shown any code nor explained how your site works and is organized but you may start looking for [Authorize] attributes (custom or default ones, as well as global action filters if this is an ASP.NET MVC 3 application) as well as <authorization> sections in your web.configs.
That's absolutely related to some custom code that runs and simply requires authentication in order to access this resource.
PM> Install-Package Glimpse
Use the tools provided by Glimpse Web Debugger to get a very clear idea of what MVC sees.
Found the issue, you was right in saying that there was an Authorize attribute placed on an action inside a controller, the controller was being called due to a Html.RenderAction() inside the View.
The reason it wasn't working for a specific user is because I allow users to add different widgets to their profile to arrange how they choose, it was a certain widget that had the Authorize attribute on.
Thought I would post back the answer in case it throws anyone else off in the future.

ASP.NET get windows username outside of page

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.

Resources