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>
I am trying to use Pgina-fork to modify windows logon. Instead of using username and password, I want to login user with a single field authentication that doesn't use a password . I am done with custom plugin modifications and building procedures but am not able to find a way to modify the logon UI. I need to hide the password field and modify other info that is not useful to me. If anyone knows how to do that in the Credential provider source code of Pgina-fork ?
You need to modify pGina Fork source Code for that.
pGina src have a folder named CredentialProvider.. that is what you need
In file credential.cpp
you can use this code
//hide password
m_fields->fields[m_fields->passwordFieldIdx].fieldStatePair.fieldState = CPFS_HIDDEN;
if (m_usageScenario == CPUS_CHANGE_PASSWORD) {
m_fields->fields[CredProv::CPUIFI_NEW_PASSWORD].fieldStatePair.fieldState = CPFS_HIDDEN;
m_fields->fields[CredProv::CPUIFI_CONFIRM_NEW_PASSWORD].fieldStatePair.fieldState = CPFS_HIDDEN;
}
This is the block of code which main pGina provides.
I am seeking some help on a telerik sitefinity backend feature. I'm creating users from a custom radgrid programatically. The code that I'm using to create a sitefinity user is as follows:
public MembershipCreateStatus AddUser(UserModel model, Role role)
{
var userManager = UserManager.GetManager();
var profileManager = UserProfileManager.GetManager()
var roleManager = RoleManager.GetManager("AppRoles");
MembershipCreateStatus status;
userManager.Provider.SuppressSecurityChecks = true;
var user = userManager.CreateUser(model.UserName, model.Password, model.Email,
model.SecretQuestion, model.SecretAnswer, true, null, out status);
if(status == MembershipCreateStatus.Success)
{
roleManager.AddUserToRole(user, role);
roleManager.SaveChanges();
var profile = profileManager.CreateProfile(user, Guid.NewGuid(),
typeof(SitefinityProfile)) as SitefinityProfile;
if (profile != null)
{
profile.FirstName = model.FirstName;
profile.LastName = model.LastName;
//Set any Data Extended Properties below
}
profileManager.RecompileItemUrls(profile);
profileManager.SaveChanges();
userManager.SaveChanges();
}
return status
}
This will let me create a sitefinity user and I can see that the user is stored in the sf_users table. The problem that I'm having is I need a way to lookup and send a user their password if they forget the password. The password is hashed and saved in an encrypted format in the table in the database. I've looked for documentation on how to change the password format to clear text or something of the sort but I've been unsuccessful in finding anything useful yet.
If anyone knows how to accomplish this so that I can save the password as clear text in the database then that would be really great.
Sitefinity Membership Provider is designed to work in similar way as the SQL Membership Provider. It supports three modes - Hashed (default), Encrypted and Clear. The Hashed format is default one. More information here: http://www.sitefinity.com/documentation/documentationarticles/developers-guide/deep-dive/security/users/password-format.
Hashed passwords are irreversible and you cannot achieve what you want using a hashed password format. Instead you can achieve this by either using the Clear (strongly not recommended) or the Encrypted (also not a good security practice).
However the CMS allows you to have reset password functionality or retrieve. Reset if Hashed format is used and retrieve if Encrypted is used. This article explains both approaches: http://www.sitefinity.com/developer-network/knowledge-base/configuring-password-recovery-in-sitefinity.
I don't know how SiteFinity works but it seems to use MembershipProvider. So the password format setting depends of the provider used and can be changed in the web.config file.
For example (http://msdn.microsoft.com/en-us/library/system.web.security.sqlmembershipprovider.aspx)
<system.web>
<membership defaultProvider="SqlProvider">
<providers>
<add
name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
passwordFormat="Clear" />
</providers>
</membership>
</system.web>
Anyway, storing password in clear way is not a good practice. Instead you should provide users an interface to reset their password. At least you should generate a new password and send them the new password (of course they must be able to change it). This way the password can be hashed before saving it in the database.
I need to reset a user password. to do so, I use the following code:
DirectoryEntry de = ..
de.AuthenticationType = AuthenticationType.Secure
de.Password = txtPassword.text
de.CommitChanges()
When i run the code - nothing happens. The user password does not change, and no exception is thrown.
if i use the following method:
de.Invoke("SetPassword", .. );
when i run the code, I get a message that says: Please insert smartcard ...
I have admin privilages over the user account.
The user does not have UAV set for smart card.
Any ideas ?
The Password property of the DirectoryEntry class isn't what you think it is. You're not changing the user's password, you're changing the password you're using to access further information from the DirectoryEntry object.
From the MSDN documentation:
You can set the Username and Password properties to specify alternate
credentials with which to access the information in Active Directory
Domain Services. Any other DirectoryEntry objects retrieved from this
instance (for example, through Children) are automatically created
with the same alternate credentials.
With your second method, if you're being asked to insert a smartcard I doubt that has anything to do with the user you're modifying - it's more likely it's asking for your smartcard. If you're not set up to use smartcards either, then I'm really not sure why it's asking you for one at all.
Take a look at this related question and see if the answers there help.
Ok, i have simple scenario:
have two pages:
login and welcome pages.
im using FormsAuthentication with my own table that has four columns: ID, UserName, Password, FullName
When pressed login im setting my username like:
FormsAuthentication.SetAuthCookie(userName, rememberMe ?? false);
on the welcome page i cant use:
Page.User.Identity.Name
to provide to user which user currently logged, BUT i dont user username like at all examples in http://asp.net web site i want to user FullName field
i think that always go to db and request fullname when page loads its crazy and dont like to user Sessions or Simple Cookie mayby FormsAuth provider has custom fields for this
I would store the user's full name in the session cookie after your call to FormsAuth
FormsAuth.SetAuthCookie(userName, rememberme);
// get the full name (ex "John Doe") from the datbase here during login
string fullName = "John Doe";
Response.Cookies["FullName"].Value = fullName;
Response.Cookies["FullName"].expires = DateTime.Now.AddDays(30);
and then retrieve it in your view pages via:
string fullName = HttpContext.Current.Request.Cookies["FullName"].Value
Forms authentication works using cookies. You could construct your own auth cookie and put the full name in it, but I think I would go with putting it into the session. If you use a cookie of any sort, you'll need to extract the name from it each time. Tying it to the session seems more natural and makes it easy for you to access. I agree that it seems a waste to go back to the DB every time and I would certainly cache the value somewhere.
Info on constructing your own forms authentication cookie can be found here.
Sorry I'm a little late to the party, but here's how you can do this without storing the value anywhere else :)
var authCookieKey = FormsAuthentication.FormsCookieName;
var responseCookies = HttpContext.Current.Response.Cookies;
var requestCookies = HttpContext.Current.Request.Cookies;
var aspxAuthCookieInResponse = responseCookies.AllKeys.Contains(authCookieKey) ? responseCookies[authCookieKey] : null;
var aspxAuthCookieInRequest = requestCookies.AllKeys.Contains(authCookieKey) ? requestCookies[authCookieKey] : null;
// Take ASPXAUTH cookie from either response or request.
var cookie = aspxAuthCookieInResponse ?? aspxAuthCookieInRequest;
var authTicket = FormsAuthentication.Decrypt(cookie.Value); // Todo: Check for nulls.
// Using the name!
var userName = authTicket.Name;
There are no custom fields for forms authentication. You'll just have to use session. That's what it's there for you know. ;) Just don't forget - forms authentication cookie and session are two independant things. They even each have their own timeouts. So the session won't be reset when a user logs out unless you do so yourself.
What about using Profiles to store the extra info with the User?
The simplest option is to use the session. By default session state is stored in memory and will be lost when the ASP.NET worker process recycles, however you can configure it to use state service instead, which retains session info in a separate process:
http://msdn.microsoft.com/en-us/library/ms178586.aspx
Another option would be to use profiles. As it sounds like you already have 'profile' information stored in your own tables, you'd probably have to write a custom provider for it so it's a more complex solution.