How to get ICredential of running user in asp.net - c#

How do I get an ICredential object within my web application?
I use Windows Authentication
I tried using the following code:
WindowsImpersonationContext securityContext =
Request.LogonUserIdentity.Impersonate();
After the last line of code both: CredentialCache.DefaultCredentials and CredentialCache.DefaultNetworkCredentials are still empty.
I know that the identity is right because the following property shows the right domain\user account I'm using:
Request.LogonUserIdentity.Name => "domain\user"
This is the authentication type of that object:
Request.LogonUserIdentity.AuthenticationType => "NTLM"

In order to get an ICredential implementation of the user, you first need to get a hold of the WindowsIdentity for the user (e.g. through Page.User.Identity). With the WindowsIdentity object you can impersonate the user. After successful impersonation you can get a hold of the credentials for the user through CredentialCache.DefaultCredentials.
The question now is, what do you want to do with the credentials? If you want to use those credentials to access some ressource on a different server you'd probably have to have Keberos delegation enabled to allow the server hop. I wouldn't know how to do that :-)

Where do you need it for?
You can retrieve the username from System.Threading.Thread.CurrentPrincipal.Identity

Related

Create user using Microsoft Graph

How do I create a user using Microsoft graph? For I am having issues with regards to permission failures during a save.
I do have few questions in mind.
Where will the user be created by calling create user API in graph ? Is it in Azure AD or somewhere else ?
I tried calling create user api by passing json and required headers, below is the error I get
Where exactly do I need to set the permission, I have already added permissions in the Application Registration Portal
But when API is executed it shows that I don't have enough permission.
FYI, I have registered the app using the same email id that I am using to test the APIs here https://developer.microsoft.com/en-us/graph/graph-explorer#
If I am not the admin, where exactly do I need to set or request for it ?
In order to create a User via Microsoft Graph, you need to request either Directory.ReadWrite.All or Directory.AccessAsUser.All permission.
Important: Directory.ReadWrite.All and Directory.AccessAsUser.All both require Admin Consent before you can use them. If you're using Graph Explorer then the URI you need to provide your tenant Admin will be generated for you. If you're doing this in your own application, you'll need to construct an Admin Consent URI yourself. You can find more details on this at v2 Endpoint & Admin Consent.
Once you have the proper permissions configured (and consented), you'll want to POST the following JSON body/payload to https://graph.microsoft.com/v1.0/users:
{
"accountEnabled": true,
"displayName": "displayName-value",
"mailNickname": "mailNickname-value",
"userPrincipalName": "upn-value#tenant-name.onmicrosoft.com",
"passwordProfile" : {
"forceChangePasswordNextSignIn": true,
"password": "password-value"
}
}
This will create a user with a temporary password. The user will be asked to set a new password as after as they authenticate for the first time.
Where will the user be created by calling create user API in graph ?
Is it in Azure AD or somewhere else ?
Yes, the user created is in the Azure AD.
I tried calling create user api by passing json and required headers,
below is the error I get
For your error, have you added the request body like the following, and this required admin:
Where exactly do I need to set the permission, I have already added
permissions in the Application Registration Portal
The required permissions to create application:
For the details, please read here.

Programmatically requesting access token on behalf of user

I want to programmatically get access token for the current user after logging in. I've figured out how to get a token using client credentials but I couldn't figure out how to get one on behalf of the user.
Here's what I tried to get using client credentials:
var client = new TokenClient("http://localhost:34240/connect/token", "client", "secret", AuthenticationStyle.PostValues);
var token = client.RequestClientCredentialsAsync(scope: "api").GetAwaiter().GetResult();
Do I need to use acr_values to add subject value to the request? If yes, how do I add it to the returned access token?
Or do I need to use code grant type instead? If yes, how do I request an authorization code programmatically?
Or is there another way that I'm missing?
I'd appreciate any help. I've checked IdentityServer samples but couldn't see anything about this.
Have a look at the Resource owner password grant examples. Basically you are doing almost the same, like you are currently doing, but instead of client credentials grant, you need to setup your client to use ResourceOwnerPassword, and then the code that you've shown, changes to:
var client = new TokenClient("http://localhost:34240/connect/token", "client", "secret", AuthenticationStyle.PostValues);
var token = client.RequestResourceOwnerPasswordAsync("<username>", "<password>", scope: "api").GetAwaiter().GetResult();
By this you are getting a token on behalf of the user. But have in mind:
The spec recommends using the resource owner password grant only for “trusted” (or legacy) applications. Generally speaking you are typically far better off using one of the interactive OpenID Connect flows when you want to authenticate a user and request access tokens.

Get UserName in Web App

I have an ASP.net app which is being hosted on a server. I want to get the Clients username from the system and use that name as a title for an XML file im saving on the server.
I have tried various different mathods such as:
Environment.UserName();
WindowsIdentity.GetCurrent();
However all that keeps returning is the NetworkService account name on the server.
Can anyone assist with this.
thank you
Given that your application has authentication set up (either Forms or Windows Authentication), you can get the current user's name via:
HttpContext.Current.User.Identity.Name
Your web application is running (by default) under the NetworkService account. If you want to know the username of the user's NT account you should check out impersonation. With that the application will be running with the credentials of the user.
For public websites this is not possible or shouldn't be done. But internal company applications could do so.
Try this:
HttpContext.Current.User.Identity.Name
This will only work if a user is authenticated by either Forms/Membership authentication or Windows, you can check beforehand:
string userName = "Anonymous";
if (User.Identity.IsAuthenticated)
userName = HttpContext.Current.User.Identity.Name
If your users are authenticated you can use User.Identity.Name
you want the user name of the web client and WindowsIdentity or Env.UserName return you the server side user name, which might be the same as the web client user name only if you have enabled authentication.
I think to solve your issue you should look in the Request headers, in one of those headers there should be a username or useragent string telling you what you need.

Fetching logged on user name from web application

IS it possible to get the windows LogOn username of client from web application.
and how does this actually works
Request.ServerVariables("LOGON_USER") also not works in this case as I don't want user to authenicate first
While
Dim ident As WindowsIdentity = WindowsIdentity.GetCurrent()
this is windows specific which gives the user where the code is?
How should I go with this.
found what I want
Context.Request.LogonUserIdentity.Name gives the logon user name..

How to tie into a domain server's login for program access rights

I need to write a program used internally where different users will have different abilities within the program.
Rather than making users have a new username and password, how do I tie into an existing domain server's login system?
Assume .NET (C#, VB, ASP, etc)
-Adam
For WinForms, use System.Threading.Thread.CurrentPrincipal with the IsInRole() method to check which groups they are a member of. You do need to set the principal policy of the AppDomain to WindowsPrincipal first.
Use this to get the current user name:
private string getWindowsUsername()
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
return Thread.CurrentPrincipal.Identity.Name;
}
And then something like this to check a role:
if (Thread.CurrentPrincipal.IsInRole("Domain Users") == true)
{}
In ASP.NET, the thread will belong to IIS, so instead you should
Set the virtual folder or website to require authentication
Get the user name supplied by the browser with Request.ServerVariables("LOGON_USER")
Use the DirectorySearcher class to find the users groups
I would use LDAP
and the DirectorySearcher Class:
http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.aspx
Assuming this is served through IIS, I would tell IIS to authenticate via the domain, but I would keep authorization (what roles a user is associated with, accessible functionality, etc) within the application itself.
You can retreive the username used to authenticate via
Trim(Request.ServerVariables("LOGON_USER")).Replace("/", "\").Replace("'", "''")
OR
CStr(Session("User")).Substring(CStr(Session("User")).LastIndexOf("\") + 1)

Categories