HttpContext.User.Identity.Name is returning blank - c#

I am trying to figure out why HttpContext.User.Identity.Name is returning blank.
Code
public ActionResult Test()
{
string username = HttpContext.User.Identity.Name;
return Content(username);
}
Am I using this in the wrong context? I am trying to get the user's username.
Web.Config
<authentication mode="Windows" />
IIS
I have enabled Anonymous and nothing else is checked. I am running IIS 6.0.
Is there any type of information I need to add to assist with figuring this out? I am pretty stuck. I checked this question but do I need to set a Cookie to make this work?

I have enabled Anonymous and nothing else is checked. I am running IIS
6.0.
This means that you won't be prompted to login, so User.Identity.IsAuthenticated will be false and User.Identity.Name will be blank.
Uncheck Anonymous Authentication and check Windows Authentication.

IsAuthenticated returns false, and thus Identity.Name returns empty string because you haven't required authentication for that action. You have to enable Windows Authentication and require authentication for the action. Try requiring that the user be authorized for the action by decorating it with the [Authorize] attribute - which will initiate the authentication negotiation.
[Authorize]
public ActionResult Test()
{
if(Request.IsAuthenticated)
{
string username = HttpContext.User.Identity.Name;
return Content(username);
}
else
{
return Content("User is not authenticated");
}
}

If anyone else is experiencing this issue, verify "Load User Profile" option is set to true. Go to IIS application pools. Select your app pool from the list. Click on Advanced Settings and scroll down to Process Model section.
This solved the problem in my case.

If you are using FormsAuthentication.SetAuthCookie
then you need to add
<authentication mode="Forms" />
to
<System.Web>
in Web.config file.
Solution from here

Related

IdentityServer4 and Angular: logout with Implicit flow

I have an Angular app that integrates with IdentityServer4 with implicit flow and the angular-oauth2-oidc library.
Everything seems to work fine, I can log in; and access token is available.
If I click the logout button, I handle it like:
logout() {
this.oauthService.logOut();
}
...and I'm redirected to Identity Server, where it asks me if I really want to log out.
My question is whether I can bypass that prompt? I mean, I want to log out completely if the button is clicked and redirected back to the Angular site, without the need to confirm it?
How can this be achieved?
EDIT: as mentioned in the other answers, it should work if you pass id_token_hint. So I did:
logout() {
this.oauthService.customQueryParams = {
'id_token_hint': this.oauthService.getIdToken()
};
this.oauthService.logOut();
}
But it doesn't make any difference.
There were two issues I needed to fix in order to make this work.
In IdentityServer, AccountOptions class, I had to set this property to true instead of false:
public static bool AutomaticRedirectAfterSignOut = true;
Next, In IdentityServer client configuration, I had to define the post logout redirect uri:
PostLogoutRedirectUris = new List<string> {"http://...."}
That did it. I did not have to change anything in the Angular client.

Avoid manual setting of FormsAuthentication cookie

I have been have bad behavior at different times using this:
FormsAuthentication.SetAuthCookie(user.UserName, true);
How does/will .Net set the cookie otherwise?
I have tried this: (System.Web.HttpContext.Current.User.Identity.IsAuthenticated fails sometimes)
But my User.Identity.IsAuthenticated is always false
What gives?
First make sure that forms authentication is enabled in your web config file.
<authentication mode="Forms" />
Use code like below to make it work. The method RedirectFromLoginPage will create the authentication cookie as well as redirect the user to the original page or the default URL i.e. home page.
if (Membership.ValidateUser(userName, password))//or whatever method you use
{
// Log the user into the site
FormsAuthentication.RedirectFromLoginPage(userName, false);
}

RedirectToaction and method calls

This is the default index function of my home controller
public ActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
return NewPosts();
}
else
{
ViewBag.Message = "Welcome!";
return View();
}
}
and this is the newposts function in the same home controller file
public ActionResult NewPosts()
{
return View();
}
I have log onto my account and I close my browser. Then I reopen it visiting the same index page, I see my identity (Welcome myusername) but the newposts function is not called and thus it doesnot display the newposts view as expected.
Why is that ? How can I fix this ?
Thank you.
I think a better way of getting this to work would be setting up a default page as 'NewPosts' for the site via the web.config. Then in your web.config, you can set the failed login page as 'Index'. This will cause users once they are log in to be sent to the 'NewPosts' page. If they close the browser (and their authentication cookie has not expired) then they will be sent to the 'NewPosts' page as well. If they are not logged in, then they will be kicked to the 'Index' page. Your if statement in your Index action method would no longer be required, as the web config forms authentication takes care of this for you in a more robust way. Here is an example of what the web config could look like:
<authentication mode="Forms">
<forms loginUrl="~/Home/Index" timeout="2880" defaultUrl="~/Home/NewPosts" >
</forms>
</authentication>
See here for more web.config info concerning forms authentication.
The problem is not about the controller, it's about caching of your browser.
If you hit Ctrl+F5 on the first page, it should recognize you as unauthorized.
I know this is not a real solution to force website visitors to hit Ctrl+F5 to refresh their browsers. There are many article in internet to tackle this kind of caching behavior, serach for them.
Two important points about your code:
1- Change return NewPosts(); to:
RedirectToAction("NewPost");
2- Decoreacte NewPosts method with [Authorize] attribute:
[Authorize]
public ActionResult NewPosts()
{
return View();
}

ASP.NET Membership Get logged on user

I had define a username in and I added it to a role.
Now, I use this code to check if user valid:
if (Membership.ValidateUser(txtUsername.Text, txtPassword.Text)) {
FormsAuthentication.SetAuthCookie(txtUsername.Text, false);
if (Roles.GetRolesForUser(txtUsername.Text).Any(role => role == "Admin")) {
Page.Response.Redirect(ResolveUrl("~/Admin/Products.aspx"));
}
txtUsername.Text = "";
}
After that, I want to check in Products.aspx page if user is in a role or not. I wrote this code but it returns my local Windows username :
Context.User.Identity.Name
I thinks it should returns logged on user.
After that I will check with this code :
if (!Context.User.IsInRole("Admin"))
{
Response.Redirect(ResolveUrl("~/Default.aspx"));
}
What's wrong with my code? How can I check for that if logged on user is in specific role?
Do you set the authentication-mode to Forms?
Web.config:
<authentication mode="Forms">
</authentication>
Also you should use Page.User.Identity.Name instead of Context.User.Identity.Name.
I believe you just need to use Page.User.Identity.Name, instead of Context.
Let me know if that does it, I've made that mix-up before =)

How to get the current user in ASP.NET MVC

In a forms model, I used to get the current logged-in user by:
Page.CurrentUser
How do I get the current user inside a controller class in ASP.NET MVC?
If you need to get the user from within the controller, use the User property of Controller. If you need it from the view, I would populate what you specifically need in the ViewData, or you could just call User as I think it's a property of ViewPage.
I found that User works, that is, User.Identity.Name or User.IsInRole("Administrator").
Try HttpContext.Current.User.
Public Shared Property Current() As
System.Web.HttpContext
Member of System.Web.HttpContext
Summary:
Gets or sets the System.Web.HttpContext object for the current HTTP request.
Return Values:
The System.Web.HttpContext for the current
HTTP request
You can get the name of the user in ASP.NET MVC4 like this:
System.Web.HttpContext.Current.User.Identity.Name
I realize this is really old, but I'm just getting started with ASP.NET MVC, so I thought I'd stick my two cents in:
Request.IsAuthenticated tells you if the user is authenticated.
Page.User.Identity gives you the identity of the logged-in user.
I use:
Membership.GetUser().UserName
I am not sure this will work in ASP.NET MVC, but it's worth a shot :)
getting logged in username: System.Web.HttpContext.Current.User.Identity.Name
UserName with:
User.Identity.Name
But if you need to get just the ID, you can use:
using Microsoft.AspNet.Identity;
So, you can get directly the User ID:
User.Identity.GetUserId();
In order to reference a user ID created using simple authentication built into ASP.NET MVC 4 in a controller for filtering purposes (which is helpful if you are using database first and Entity Framework 5 to generate code-first bindings and your tables are structured so that a foreign key to the userID is used), you can use
WebSecurity.CurrentUserId
once you add a using statement
using System.Web.Security;
We can use following code to get the current logged in User in ASP.Net MVC:
var user= System.Web.HttpContext.Current.User.Identity.GetUserName();
Also
var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //will give 'Domain//UserName'
Environment.UserName - Will Display format : 'Username'
This page could be what you looking for:
Using Page.User.Identity.Name in MVC3
You just need User.Identity.Name.
Use System.Security.Principal.WindowsIdentity.GetCurrent().Name.
This will get the current logged-in Windows user.
For what it's worth, in ASP.NET MVC 3 you can just use User which returns the user for the current request.
If you are inside your login page, in LoginUser_LoggedIn event for instance, Current.User.Identity.Name will return an empty value, so you have to use yourLoginControlName.UserName property.
MembershipUser u = Membership.GetUser(LoginUser.UserName);
You can use following code:
Request.LogonUserIdentity.Name;
IPrincipal currentUser = HttpContext.Current.User;
bool writeEnable = currentUser.IsInRole("Administrator") ||
...
currentUser.IsInRole("Operator");
var ticket = FormsAuthentication.Decrypt(
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
if (ticket.Expired)
{
throw new InvalidOperationException("Ticket expired.");
}
IPrincipal user = (System.Security.Principal.IPrincipal) new RolePrincipal(new FormsIdentity(ticket));
If you happen to be working in Active Directory on an intranet, here are some tips:
(Windows Server 2012)
Running anything that talks to AD on a web server requires a bunch of changes and patience. Since when running on a web server vs. local IIS/IIS Express it runs in the AppPool's identity so, you have to set it up to impersonate whoever hits the site.
How to get the current logged-in user in an active directory when your ASP.NET MVC application is running on a web server inside the network:
// Find currently logged in user
UserPrincipal adUser = null;
using (HostingEnvironment.Impersonate())
{
var userContext = System.Web.HttpContext.Current.User.Identity;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["AllowedDomain"], null,
ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);
adUser = UserPrincipal.FindByIdentity(ctx, userContext.Name);
}
//Then work with 'adUser' from here...
You must wrap any calls having to do with 'active directory context' in the following so it's acting as the hosting environment to get the AD information:
using (HostingEnvironment.Impersonate()){ ... }
You must also have impersonate set to true in your web.config:
<system.web>
<identity impersonate="true" />
You must have Windows authentication on in web.config:
<authentication mode="Windows" />
In Asp.net Mvc Identity 2,You can get the current user name by:
var username = System.Web.HttpContext.Current.User.Identity.Name;
In the IIS Manager, under Authentication, disable:
1) Anonymous Authentication
2) Forms Authentication
Then add the following to your controller, to handle testing versus server deployment:
string sUserName = null;
string url = Request.Url.ToString();
if (url.Contains("localhost"))
sUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
else
sUserName = User.Identity.Name;
If any one still reading this then, to access in cshtml file I used in following way.
<li>Hello #User.Identity.Name</li>

Categories

Resources