Sharepoint - Impersonating App Pool Identity - sharepoint

I'm using the SPSecurity.RunWithElevatedPrivileges.... allow to "impersonate" the super user "sharepoint\system" account.
Is the "sharepoint\system" account is an alias of the app pool identity of the current web application?
So if my app pool identity is a custom user (with email and other information), how can i retrieve its information? (the information i'm trying to get is the email address...the custom app pool user email has a value, the "sharepoint\system" account email has no value!!!)
I also tried to retrieve the appPool identity by using the WindowsIdentity.Impersonate(IntPtr.Zero) method but...nothing!
So any ideas????

Points to note:
The code that runs in the SPSecurity.RunWithElevatedPrivileges delegate method runs under the SharePoint\System account
SharePoint\System account has super user privileges. However it is recognized within the SharePoint run time environment but not by the windows security system, i.e. it doesn't represent the account under which the AppPool is running
When tried to access the resources outside the SP Environment such as Server File system/ DB then only the AppPool Identity comes into picture
If you want to access the e-mail address of the user account under which the AppPool is running, you may try...
SPSecurity.RunWithElevatedPrivileges(delegate {
using (SPSite siteCollection = new SPSite("Url"))
{
using (SPWeb site = siteCollection.OpenWeb())
{
Console.WriteLine(string.Format("Current Logged in User is {0}. And Email Id: {1} ", site.CurrentUser.LoginName ,site.CurrentUser.Email));
appPoolAccount = siteCollection.WebApplication.ApplicationPool.Username;
SPUser appPoolUser = site.Users[appPoolAccount] as SPUser;
Console.WriteLine(string.Format("AppPool User is {0}. And Email Id: {1} ", appPoolUser.LoginName, appPoolUser.Email));
Console.ReadKey();
}
}
});
The output will look like...
So If you really want to get the EmailId of the AppPool account, pick the user explicitly and access the Email property of the SPUser object as I did above..

Related

How can I allow a service account to access my REST API when using Roles-based Authorization in Azure?

Summary: I have a REST API that I use for functional testing. I only allow people or groups in a specific "Tester" role to hit the API. I want to trigger this functional testing during an Azure DevOps Release Pipeline automatically, but I can't figure out how to authorize the machine account to hit the API.
Details:
I have this API secured with [Authorize(Roles = "Tester")]
[Route("quotas/developers")]
[HttpGet]
[Authorize(Roles = "Tester")]
[SwaggerResponse(HttpStatusCode.OK, "Successful operation", Type = typeof(DeveloperQuota[]))]
public async Task<List<DeveloperQuota>> GetDeveloperQuota([FromUri]string developerUpn)
To set this up, I have an Enterprise Application registered in Azure Active Directory. In the manifest, I declare the role.
And then in the Enterprise Application I add some users and groups which are assigned the role "Tester."
This works fine for running my functional tests by hand. I run the tests, it pops up an oauth dialog for me to enter my credentials, it grabs my Bearer token from the successful auth request then passes it along to the APIs.
private string GetActiveDirectoryToken()
{
string authority = this.configuration.ActiveDirectoryAuthority;
string resource = this.configuration.ActiveDirectoryAudience;
string keyVaultUri = this.configuration.KeyVaultUri;
IKeyVaultAdapterFactory keyVaultAdapterFactory = new KeyVaultAdapterFactory();
var keyVaultAdapter = keyVaultAdapterFactory.CreateInstance(KeyVaultServicePrincipal.PowerShellAppId);
SecureString clientIdSecure = keyVaultAdapter.GetAzureKeyVaultSecretSecure(keyVaultUri, "GasCallbackRegistrationClientID", null).Result;
SecureString redirectUriSecure = keyVaultAdapter.GetAzureKeyVaultSecretSecure(keyVaultUri, "GasCallbackRegistrationClientIDRedirectUri", null).Result;
var authContext = new AuthenticationContext(authority);
var result = authContext.AcquireTokenAsync(
resource,
SecureStringUtilities.DecryptSecureString(clientIdSecure),
new Uri(SecureStringUtilities.DecryptSecureString(redirectUriSecure)),
new PlatformParameters(PromptBehavior.Auto)).Result;
return result.AccessToken;
}
Of course, if I'm running this during automation, there will be nothing to fill in the dialog with creds, nor do I want to be storing a copy of these creds, especially since these creds roll on a schedule which are maintained elsewhere.
My thought was that I could create an Azure Service Principal, associate a cert with the service principal, install the cert on my deployment machine, login as the Service Principal if the cert was available, and then put that Service Principal in the "Tester" role. The problem is I can't add a Service Principal as a user in the Enterprise Application. It only appears to allow me to add "Users and groups." I similarly can't add a service principal to a group.
Any thoughts on how I can authorize my deployment box to hit these APIs?
Roles published for applications are treated as application permissions and not assignable to other apps via the "Users and Groups" assignment screen.
To assign the app permissions to a client app, go to the client app's registration page, click on Api Permissions and then Add a Permission. Select the My Api tab, search for your application that published the app roles and you'd see the app role listed in the list below. Select that, save and then grant admin consent.

OWIN Mixed Authentication IIS Issue

I have a project where Windows Authentication and Forms login are required. I came across OWIN Mixed Authentication which seems to meet my requirements.
Before implementing into my own project I tried running the sample solution from the source link.
I debugged the solution using IIS Express and when I entered my credentials into the windows authentication dialog my correct credentials where found in the logonUserIdentity variable.
But when I set up a local IIS site add set the following feature delegation property as stated in the readme file:
Authentication - Windows to Read/Write
When I entered my credentials into the windows authentication dialog NT AUTHORITY\IUSR is coming through in the logonUserIdentity variable instead of the username I entered in the dialog.
I feel this happening because AllowAnonymous is enabled on the IIS site but its needed to stop a login loop that occurs because of the CookieAuthentication within the Startup.Auth class.
How should I be setting up my IIS site so that the windows credential dialog passes through the entered credentials and not NT AUTHORITY\IUSR.
I debugged the solution using IIS Express and when I entered my credentials into the windows authentication dialog my correct credentials where found in the logonUserIdentity variable.
As far as I know, the IIS express use current computer login account as the Anonymous login account. So you will find the logonUserIdentity is right. You could try to login the application with different domain account. You will find it still use current computer login account not changed to the login user account.
Since the mix auth allow multiple ways to login,you should always enable anonymous login to let the person who doesn't have the domain account.
The mix own auth use asp.net identity external login to achieve login with windows.The asp.net identity external login will firstly go to the mixauth provider to check the windows auth result.
If success, it will go back to the account controller's ExternalLoginCallback method with the windows info and use this info the identity will generate an identity user.
In my opinion, if you want to get the current login in user, I suggest you could try to use session to store the windows login in user's account in ExternalLoginCallback method.
More details, you could refer to below codes:
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
Session["LoginonUsername"] = loginInfo.DefaultUserName;
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
Result:
My IIS site binding was set to http://projectname
When I changed the binding on the IIS site to http://localhost or http://pcname it was allowing me to pass through the correct windows credentials.

How to use Login User credentials to call exchange web service in sharepoint for fetching user mail box?

I don't want to use default credentials because I need to fetch log in user Mail Box information therefore, to call Exchange Web Service I need Log in User credentials. So how can I get current Logged-in user credentials??
Constructor of calling exchangeweb service is as below:
ExchangeServiceBinding exchangeService = new ExchangeServiceBinding()
exchangeService.RequestServerVersionValue = new RequestServerVersion();
exchangeService.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2010;
exchangeService.Credentials = new NetworkCredential("user_LoginID", "LoggedIn_user_password");
you can't access the user password or the credentials from SharePoint directly. You're able to get something like SPContext.Current.Web.CurrentUser.LoginName, but you won't be able to hand over the user password, if UseDefaultCredentials doesn't work for the EWS.

How to get the user name using a Microsoft user id?

Am working on a windows store javascript application. I have used the microsoft login authentication from azure as follows.
client.login("microsoftaccount").done(function (results) {;
userId = results.userId;
refreshTodoItems();
var message = "You are now logged in as: " + userId;
var dialog = new Windows.UI.Popups.MessageDialog(message);
dialog.showAsync().done(complete);
}
Am able to retreive the userid such as "Microsoftaccount:c2892313bla...."
How am I supposed to retreive the associated UserName for that Microsoft account ID?
When you're logged on, on any scripts on the server side you can query for the identities of the user (via the user.getIdentities() function), which will give you an object with access tokens which you can use to talk to the authentication providers. The post at http://blogs.msdn.com/b/carlosfigueira/archive/2012/10/25/getting-user-information-on-azure-mobile-services.aspx has an example on how to get the user name for MS account (and other providers as well).

Microsoft CRM 2011 Impersonation

I want to know in CRM 2011, if I initiated the organization service with user (A) and then I impersonated with user (B).
Which user permissions will be used by CRM when I try to execute a request (i.e create account, ...)?
For example:
I have
User (A) who don't have permissions to act on behalf another user.
User (B) who have system administrator permissions and act on behalf another user permission.
I create the organization service based on Windows Authentication and log-in with user (A) as following:
Uri organizationUri = new Uri("http://localhost:5555/RMS/XRMServices/2011/Organization.svc");
Uri homeRealmUri = null;
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
Then I impersonate like that
orgProxy.CallerId = userBGuid;
When I am trying to execute WhoAmIRequest; I get the following error:
System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: User does not have the privilege to act on behalf another user. (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).
When I give User (A) permissions to act on behalf of another user, this code pass successfully.
It looks it's expected behavior. If you set CallerId = userBGuid it means that even when you are logged as userA, all activities done on behalf of userB. UserA should have priviliges to do this.

Resources