Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find the users name/Identity in C#

I need to programatically find the users name using C#. Specifically, I want to get the system/network user attached to the current process. I'm writing a web application that uses windows integrated security.

like image 322
minty Avatar asked Dec 09 '08 00:12

minty


People also ask

What is user identity in C#?

Identity is Users Authentication and Authorization. In this article we will see how users are able to log in with their social identities so that they can have a rich experience on their website. Description. Identity is Users Authentication and Authorization.

How do I find my UserName in net core?

Getting Current UserName in Controller Getting UserName in Controller is easy as you can directly access the HttpContext object within Controller. You need to access HttpContext.User.Identity.Name property to access the username.

What is HttpContext current user identity name?

It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.

Is user A identity?

A user identification or user ID is an entity used to identify a user on a website, software, system or within a generic IT environment. It is the most common authentication mechanism used within computing systems.


1 Answers

The abstracted view of identity is often the IPrincipal/IIdentity:

IPrincipal principal = Thread.CurrentPrincipal;
IIdentity identity = principal == null ? null : principal.Identity;
string name = identity == null ? "" : identity.Name;

This allows the same code to work in many different models (winform, asp.net, wcf, etc) - but it relies on the identity being set in advance (since it is application-defined). For example, in a winform you might use the current user's windows identity:

Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

However, the principal can also be completely bespoke - it doesn't necessarily relate to windows accounts etc. Another app might use a login screen to allow arbitrary users to log on:

string userName = "Fred"; // todo
string[] roles = { "User", "Admin" }; // todo
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(userName), roles);
like image 168
Marc Gravell Avatar answered Oct 11 '22 12:10

Marc Gravell