Getting the GUID of the current user? - asp.net

I want to add a user's GUID in with the information I retrieve from a user when they submit a post. How can I get the GUID?
I am using the default authentication system that comes along with an ASP.NET MVC application.

If you are using the ASP.NET Membership provider:
MembershipUser user = Membership.GetUser(User.Identity.Name);
Guid guid = (Guid)user.ProviderUserKey;
or simply:
Guid guid = (Guid)Membership.GetUser().ProviderUserKey;

You could simply use the username instead of hitting the database for something like this:
[Authorize]
public ActionResult PostComment()
{
var username = User.Identity.Name;
// Here you know the user trying to post a comment
...
}

Hi there is a MVC use of the Membership example, with explanation in this blog. It shows how you can get the membership information of current logged in user.

This is how to get the user guid from the user name:
Guid userGuid = (Guid)Membership.GetUser(user.Username).ProviderUserKey;

Related

How can I isolate users' data in ASP.net MVC application?

So I have an asp.net application (using MVC5, ASP 4.5, EF) deployed on Azure. The application allows users to register and login.
However, once logged in, anyone can see everyone else's data.
What is the best practice to isolate the data belonging to different users so that each user can only see the data he/she creates?
Another small question is how does Facebook separates its users' data?
Thanks
For every piece of data a user creates, store their user ID and only allow users to see data that has their user ID. A couple of examples:
SQL:
SELECT UserDataID, Value FROM UserData WHERE UserID = #UserID;
Pass in the user's id to the #UserID parameter.
LINQ:
using (var entityFrameworkContext = new MyDataEntities())
{
var currentUserData = entityFrameworkContext.UserData.Where(userData -> userData.UserID = currentUserID);
}
Where currentUserID could be the user name or ID from forms authentication, for example: HttpContext.Current.User.Identity.Name.
The way in which I accomplished this was by the following.
In your controller you will need to use
public ActionResult Index()
{
var currentUser = manager.FindById(User.Identity.GetUserId());
return View(db.ToDoes.ToList().Where(todo => todo.User.Id == currentUser.Id));
}
You can then also create an admin role which can then view all the details of users and return ToList(). You then might want to put an [Authorize] method on it to only allow Admins access.
[Authorize(Roles="Admin")]
public async Task<ActionResult> All()
{
return View(await db.ToDoes.ToListAsync());
}
I found the following project of great help in understanding. https://github.com/rustd/AspnetIdentitySample
Hope this is of some help

howto get the user id from a FormsAuthentication page in asp.net MVC?

i made a webpage which use FormsAuthentication. now i need to get the user id of the user (if a user is logged in)
how to get these? i tryed to access it via the FormsAuthentication but there is no method liks: getUserId()
any solutions?
by the way, i need the id in my controller not in my view.
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
var id = HttpContext.Current.User.Identity.Name;
// Do stuf...
}

Asp.net MVC3 + Code First + Custom Membership Users and Provider classes?

I'm using ASP.NET MVC3 with EF Code First. I'm new to both tech, so please be gentle!
I have a requirement that I will need additional properties for the User (such as company name, first/last name etc). I also need to be able to store the Membership information in databases other than SQL Server. So I am looking into custom membership user and provider classes. Except I just do not know how that would work with EF Code First.
My custom user class is extending MembershipUser. And I have a custom extension of the MembershipProvider class. Within the provider, I'd like to use my DBContext class to get User information, but I can't seem to get it working correctly. Please can somebody guide me?
Thanks
This is how I get the user in my implementation:
public override System.Web.Security.MembershipUser GetUser(string username, bool userIsOnline)
{
MyUser user = MyUserController.get(username);
if (user == null)
return null;
MembershipUser mUser = new MembershipUser("MyMembershipProvider",
user.Login,
user.Id,
user.Email,
null, null, true, false,
user.CreateDate,
DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);
return mUser;
}
Is this what you are looking for?
Hope it helps.

HttpContext.User.Idenity is empty

I'm using asp.net and trying to assign roles for a user with forms authentication like this:
public ActionResult AdminLogin(string password, string username)
{
User _user = _us.GetUsers(username, password).FirstOrDefault();
if (_user != null)
{
string _username = _user.Username;
FormsAuthentication.SetAuthCookie(_username, false);
string[] _roles = _us.GetUserRoles(_username);
HttpContext.User = new GenericPrincipal(HttpContext.User.Identity, _roles);
return RedirectToAction("Index", "Admin");
When I debug HttpContext.User.Identity always is null, but _username and _roles contains the proper data. Howto fix this?
/M
Your action is setting the User IPrincipal for the current context. As soon as you redirect to your other action (and all subsequent requests) a new HttpContext is created with a null User IPrincipal.
What you could do is persist the information in the authentication cookie and then extract that data in the Application_AuthenticateRequest method in your Global.asax file and set the User property of the HttpContext there.
This answer contains more details and example code
I believe the issue is that you are just setting the user as authenticated, and therefore, the HttpContext is not updated yet since the auth cookie has not yet been set on the users side of the request.
I was struggling too.
I was trying to carryout my authentication and authorization inside a WCF service using standard ASP.Net Membership and Role providers.
I wanted to pass in credentials and a 'requested app' to determine if the user 'authenticated' for that app. (not the ASP.Net APP, but an app in my own database).
To do this, I wanted access to the roles, but didn't want to 'redirect' or have a second call to my WCF service.
Here is some code that works for me:
First I determine if the user is valid as follows:
if (Membership.ValidateUser(CompanyCn, CompanyPwd))
{
sbLogText.AppendFormat("\r\n\r\n\tValid User UID/PWD: '{0}'/'{1}'", CompanyCn, CompanyPwd);
FormsAuthentication.SetAuthCookie(CompanyCn, false);
}
Then the following code workes nicely for getting the list of roles:
List<string> roleList = new List<string>(Roles.GetRolesForUser(CompanyCn));
sbLogText.AppendFormat("\r\n\r\n\tUser ('{0}'): Roles ({1}):", CompanyCn, roleList.Count);
foreach (string s in roleList)
sbLogText.AppendFormat("\r\n\t\tRole: {0}", s);

How do you get the UserID of a User object in ASP.Net MVC?

I have some tables that have a uniqueidentifier UserID that relates to aspnet_Users.UserID. When the user submits some data for those tables, since the controller method has an [Authorize] I get a User object. I can get the username with User.Identity.Name, but how do I get the UserID to be able to establish (the ownership) relationship?
It seems you cannot get it from the User object but you can get it this way:
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
Here is the solution:
Include:
using Microsoft.AspNet.Identity;
Then use extension methods:
User.Identity.GetUserId();
Firstly, this answer is not strictly an MVC answer, but an ASP.NET answer. The fact that your site is MVC is irrelevant to solving the problem, in this case.
Hmm. I'm not very sure how you are handling your users in your system but it sounds like you using the (very evil) asp.net membership provider that comes out of the box with .net. This is hinted by the fact that you said
aspnet_Users.UserID
UserID is a uniqueidentifier (read: GUID).
With the default forms authentication system, which uses the default FormsIdentity, it only has a single property called Name (as you correctly noted). This means it has only one value where to place some unique user information. In your case, you are putting Name/UserName/DisplayName, in the Name property. I'm assuming this name is their Display Name and it is unique. Whatever value you are putting in here, it HAS TO BE UNIQUE.
From this, you can grab the user's guid.
Check this out.
using System.Web.Security;
....
// NOTE: This is a static method .. which makes things easier to use.
MembershipUser user = Membership.GetUser(User.Identity.Name);
if (user == null)
{
throw new InvalidOperationException("User [" +
User.Identity.Name + " ] not found.");
}
// Do whatever u want with the unique identifier.
Guid guid = (Guid)user.ProviderUserKey;
So, every time you wish to grab the user information, you need to grab it from the database using the static method above.
Read all about the Membership class and MembershipUser class on MSDN.
Bonus Answer / Suggestion
As such, i would CACHE that result so you don't need to keep hitting the database.
... cont from above....
Guid guid = (Guid)user.ProviderUserKey;
Cache.Add(User.Identity.Name, user.UserID); // Key: Username; Value: Guid.
Otherwise, you can create your own Identity class (which inherits from IIdentity) and add your own custom properties, like UserID. Then, whenever you authenticate (and also on every request) you can set this value. Anyway, this is a hard core solution, so go with the caching, right now.
HTH
User.Identity is an IPrincipal - typically of type System.Web.Security.FormsIdentity
It doesn't know anything about UserIDs - it's just an abstraction of the concept of an 'identity'.
The IIdentity interface only has 'Name' for a user, not even 'Username'.
If you're using MVC4 with the default SimpleMembershipProvider you can do this:
WebSecurity.GetUserId(User.Identity.Name) // User is on ControllerBase
(Where WebSecurity is in the nuget package Microsoft.AspNet.WebPages.WebData in WebMatrix
You can also use
WebSecurity.CurrentUserName
WebSecurity.CurrentUserId
(if you're using ASPNetMembershipProvider which is the older more complex ASPNET membership system then see the answer by #eduncan911)
If you are using the ASP.NET Membership (which in turn uses the IPrincipal object):
using System.Web.Security;
{
MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name);
Guid guid = (Guid)user.ProviderUserKey;
}
User.Identity always returns the state of the current user, logged in or not.
Anonymous or not, etc. So a check for is logged in:
if (User.Identity.IsAuthenticated)
{
...
}
So, putting it all together:
using System.Web.Security;
{
if (User.Identity.IsAuthenticated)
{
MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name);
Guid guid = (Guid)user.ProviderUserKey;
}
}
Best Option to Get User ID
Add Below references
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;*
public myFunc()
{
.....
// Code which will give you user ID is
var tmp = User.Identity.GetUserId();
}
If you are using your own IPrincipal object for authorization, you just need to cast it to access the Id.
For example:
public class MyCustomUser : IPrincipal
{
public int UserId {get;set;}
//...Other IPrincipal stuff
}
Here is a great tutorial on creating your own Form based authentication.
http://www.codeproject.com/KB/web-security/AspNetCustomAuth.aspx
That should get you on the right path to creating an authentication cookie for your user and accessing your custom user data.
using System.Web.Security;
MembershipUser user = Membership.GetUser(User.Identity.Name);
int id = Convert.ToInt32(user.ProviderUserKey);
Its the ProviderUserKey property.
System.Web.Security.MembershipUser u;
u.ProviderUserKey
Simple....
int userID = WebSecurity.CurrentUserId;
Usually you can just use WebSecurity.currentUserId, but if you're in AccountController just after the account has been created and you want to use the user id to link the user to some data in other tables then WebSecurity.currentUserId (and all of the solutions above), unfortunately, in that case returns -1, so it doesn't work.
Luckily in this case you have the db context for the UserProfiles table handy, so you can get the user id by the following:
UserProfile profile = db.UserProfiles.Where(
u => u.UserName.Equals(model.UserName)
).SingleOrDefault();
I came across this case recently and this answer would have saved me a whole bunch of time, so just putting it out there.

Resources