Remove the domain name from User.Identity.Name - asp.net

I have he following method inside my action method:-
repository.InsertOrUpdateRack(rj.Rack, User.Identity.Name, assetid);
But the user name generated from User.Identity.Name will prefix the username with the domain name as follow:-
DOMAINNAME\username
So is there a way to force the User.Identity.Name to retrieve the username only?
Thanks.

The domain forms part of the username so I don't think any of the methods/properties return what you need. Can you not just do:
var userName = User.Identity.Name.Split('\\')[1];
Not ideal but simple enough. If you want to keep it nicely hidden away you could create an extension method on IIdentity.
The VB equivalent is (where UserWindowsName could be a variable or control used to display the Windows User Name):
Dim userName As WindowsIdentity = HttpContext.Current.Request.LogonUserIdentity
UserWindowsName = userName.Name.Split("\"c)(1)

var name = Regex.Replace(HttpContext.User.Identity.Name, #"^.*\", "");

Related

How to get IdentityUser by Username

I have previously worked with Membership through "System.Web.Security.Membership"
Here, you can do the following:
var currentUser = Membership.GetUser();
var otherUser = Membership.GetUser(username);
...giving you a MembershipUser.
Now, with Identity, I can find a load of ways to get the current logged in user.
But no way to get another user.
I can use:
var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
var user = userManager.Find(username, password);
But that takes both username and password, with no overload for just username.
How do i get the IdentityUser from only a username?
Almost every answer I find is connected to MVC.
This is for a WCF service, where authorization is made using Identity. And in some cases the user is getting to the site from an other site with a generated "token" - an encrypted string, containing the username. From here, user is logged in and a session-cookie is set, depending on users settings.
Also, is there a shorter way to get UserInformation?
"var currentUser = Membership.GetUser(username);"
is much more convenient than
"var user2 = (new UserManager((new UserStore()))).Find(username, password);"
UserManager has UserManager<TUser>.FindByNameAsync method. You can try using it to find user by name.

LDAP user attribute request returns unusual results

I'm struggling to return user details from AD using LDAP, after i have authenticated that the user exists.
I am using a simple auth method as follows:
Function AuthenticateUser(path As String, user As String, pass As String) As Boolean
Dim de As New DirectoryEntry(path, user, pass, AuthenticationTypes.Secure)
Try
Dim ds As DirectorySearcher = New DirectorySearcher(de)
Dim result As SearchResult = ds.FindOne()
If result Is Nothing Then Return False
'>>DEBUG OUTPUTS ONLY:
displayName.Text = result.GetDirectoryEntry().Properties.Item("distinguishedName").Value
displayName.Text += result.GetDirectoryEntry().Properties("name").Value
Return True
Catch
Return False
End Try
End Function
the problem is that "distinguishedName" returns "DC=our-domain,DC=co,DC=uk"
and "name" returns just "our-domain", not the name of the user that has just been auth'ed
Note: the displayName.text outputs are purely for debug purposes
I have tried various combos of requests but nothing seems to return USER details.
ETA: to the security police: this is all within a https connection, I'm not sending passwords about in plain text!
1. Dim de As New DirectoryEntry(path, user, pass, AuthenticationTypes.Secure)
2. Try
3. Dim ds As DirectorySearcher = New DirectorySearcher(de)
4. Dim result As SearchResult = ds.FindOne()
Line 1 is basically creating a DirectoryEntry element, that refers to the object at path. The only purpose that the username and password parameters serve is to authorise access to whatever entity path refers to.
As you currently have things, you're binding to the domain, not to the user (but you're authorised to connect to the domain as that user).
You then, in line 3, create a DirectorySearcher. But the constructor you're using just says to root the search at de (which as we've established, is just the domain). You've not done anything yet to search for that particular user within the domain - they could be connecting to perform almost any kind of search imaginable.
What you might want to do is look at the overload of DirectorySearcher that accepts a filter parameter - and provide a filter parameter that restricts the search to just the user. I don't know what form your user parameter is in - if it is, say, in the form of a user principal name (user#domain), you might try specifying a filter of:
Dim ds As DirectorySearcher = New DirectorySearcher(de,"(userPrincipalName=" + user + ")")
If you have just a username, you'd want to search against sAMAccountName. If you have an older style domain name (domain\user), then usually you want to split that on \, discard the domain name, and still search on sAMAccountName.
Some (but not too much!) help on constructing the filter parameters is found in the Filter property documentation.

ASP.NET Membership: Where is Current User ID Stored?

Using ASP.NET membership, if I want to get information for the current user, I can call MembershipUser.GetUser()
So, somehow the system must know the ID of the current user.
If this is correct, and all I want is the ID of the current user, is there a way to get it without returning all the user information from the database?
I know I can get the username of the current user using User.Identity.Name, but I need the ID.
The short answer is no you can't get only userID without retrieve whole user info when you use built-in membership provider, only by this
MembershipUser user = Membership.GetUser();
string UserID = user.ProviderUserKey.ToString();
But if you want to have method or property which retrieve only userID, you must re-implement your own membership provider or(it's simply) to implement IPrincipal interface
To return the UserId, use the command bellow in your controller:
User.Identity.GetUserId();
To return the UserName, use:
User.Identity.Name;
To return the user:
var user = db.Users.Find(User.Identity.GetUserId());
Please refer to the post: How to get current user, and how to use User class in MVC5?
As you've guessed, the Membership API doesn't support what you want out of the box. In the past, I've used a helper class instead of creating my own provider. In this case it's pretty simple, maybe something like this:
public static object GetUserId() {
return GetUserId(HttpContext.Current.User.Identity.Name, true);
}
public static object GetUserId(string userName) {
return GetUserId(userName, true);
}
public static object GetUserId(string userName, bool UpdateLastActivity) {
using (SqlConnection c = new SqlConnection(CONNECTION_STRING)) {
string sql = #"
DECLARE #UserId uniqueidentifier
SELECT #UserId=u.UserId
FROM dbo.aspnet_Applications AS a
,dbo.aspnet_Users AS u
,dbo.aspnet_Membership AS m
WHERE
a.LoweredApplicationName=LOWER(#ApplicationName)
AND u.ApplicationId=a.ApplicationId
AND u.LoweredUserName=LOWER(#UserName)
AND u.UserId=m.UserId;
IF #UserId IS NOT NULL AND #UpdateLastActivity=1
UPDATE dbo.aspnet_Users
SET LastActivityDate=#CurrentTimeUtc
WHERE UserId=#UserId;
SELECT #UserId
";
using (SqlCommand cmd = new SqlCommand(sql, c)) {
cmd.Parameters.AddWithValue("#ApplicationName", Roles.ApplicationName);
cmd.Parameters.AddWithValue("#UserName", userName);
cmd.Parameters.AddWithValue("#UpdateLastActivity", UpdateLastActivity);
cmd.Parameters.AddWithValue("#CurrentTimeUtc", DateTime.UtcNow);
object id = null;
c.Open();
id = cmd.ExecuteScalar();
return id != DBNull.Value ? id : null;
}
}
}
Above is pretty similar to what's done in the Membership API when calling GetUser()
You can use MembershipUser.UserName to get the user id or try calling Membership.GetUser(User.Identity.Name) and see if that works for you.
After looking into this further, it seems that the ASP.NET Membership API does not track the user ID after all. It must track just the user name (User.Identity.Name). The ID is not required because Membership.GetUser() can find a user from an ID or user name.
In fact, Membership.GetUser() must simply translate to Membership.GetUser(User.Identity.Name). Since it can obtain the current user from the user name, there is no longer any reason to assume that the current user ID is cached anywhere.
So it appears the ID is not loaded into memory, and the only way to obtain the ID is to load the data from the database (which means loading the entire user record when using the ASP.NET Membership API).
Consider
int userId = WebSecurity.CurrentUserId;
Credit: https://stackoverflow.com/a/15382691/1268910

redirecting pages using session

i'm new to ASP.NET,so plz b patient :D
i want to redirect one of my pages to the other one,and i keep the username!
i tried to use session.add and session[],but when i want to insert the username inside the brackets,it says use must int!!!but i thought i should use session["username"]
i used another way(request.querystring[]),but both have problems
here is my code
//first solution
string username="asal";
session.Add(username,username);
Response.Redirect("~/Doctor/DoctorsMainPage.aspx");
//in the other page
Label1.Text= Session["username"].ToString();//this one says use int?!
//i used this one instead of it
Label1.Text= Session[0].ToString();//with this one i get the username in other page,but one i want to pass another string like "id" with session,I can not!
//the second solution
string username="asal";
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username");
Label1.Text = Request.QueryString["username"];//this one redirect to doctors main page but set the value of username to "" !
session.Add(string, string) where the first string is the name of the variable and the second is the value.
You are adding the value twice.
//first solution
string username="asal";
session.Add("username",username); <-- this is your problem
Response.Redirect("~/Doctor/DoctorsMainPage.aspx");
//in the other page
Label1.Text= Session["username"].ToString();
Now, as for
//the second solution
string username="asal";
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username");
Label1.Text = Request.QueryString["username"];//this one redirect to doctors main page but set the value of username to "" !
In this case you're creating a url "~/Doctor/DoctorsMainPage.aspx?username"
Ok - so what is username? The code is looking for a param in the query string named username but it's not finding a value.
You need:
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username="+username);
That will give you "~/Doctor/DoctorsMainPage.aspx?username=asal"
string username = "asal";
Session["username"] = username;
Response.Redirect("~/Doctor/DoctorsMainPage.aspx");
//Other page
Label1.Text = Session["username"].ToString().Trim();
You have to add the session like..
session.Add("username",username); instead session.Add(username,username);
And then you can access the value like..Label1.Text= (String)Session["username"];
Check out this article related to the session State ASP.NET Session State Overview that will help you to understand Session State management.
Seconly querystring should be like, as you have not passing your string parameter and it should be like...
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username=" + username);

How to Get List of User/Profile from Membership Provider?

I am utilising this Membership Provider. I am stuck with getting the User List + Profile (FirstName, LastName, Title etc etc)
I know that there is a method for Membership.GetAllUsers() but I don't know how to combine this with FirstName, LastName that I stored in Profile Provider.
Thanks
Membership.GetAllUsers() returns a MembershipUserCollection, which you can use to access individual MembershipUser. Example:
MembershipUserCollection users = Membership.GetAllUsers();
string email = users["some_username"].Email;
You can also retrieve ProfileInfo in the similar way:
ProfileInfoCollection profiles = ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All);
DateTime lastActivity = profiles["some_username"].LastActivityDate;
However there are no FirstName and LastName properties by default, unless you manually specified them in your profile provider.
Check out MembershipUser class and ProfileInfo class for more details. You might also wanna check out SqlProfileProvider class as an example of profile provider, unless you already have implemented one.
First when you create a user, create a profile with the same username using:
// Create an empty Profile for the new User
ProfileCommon p = (ProfileCommon) ProfileCommon.Create("username", true);
Then to retrieve it next time..
// Retrieve a particular profile
ProfileCommon userProfile = Profile.GetProfile("username");
Thanks.

Resources