SharePoint Provider Apps High Security why Windows Auth - authentication

I have setup a SharePoint dev environment and managed to get a provider hosted app working with Certs etc (High Security)
This is all on-premise and we won't have a connection to ACS (now, I may have miss understood ACS, I presume its azure based and servers need to talk to server outside of the server room :) ).
My problem is:
The SharePoint site will not be using Windows Auth, we will be using a login form which will read details from another store.
If I review the code that VS generates I can see that it expects a Windows identity.
Can this be done? I would have expected my provider app not to need any auth as its hosted via SharePoint, it gets the claim from SharePoint so why does it need a Windows Identity as well as the SharePoint Claims.

As you said : The SharePoint site will not be using Windows Auth, we will be using a login form which will read details from another store.
Ans : You are talking about Form based authentication.
If I review the code that VS generates I can see that it expects a Windows identity.
Ans : You are correct. VS generates the code that expects windows identity [For dev environments]. You need to write separate function to get clientcontext for FBA using SharePointContextProvider class.
Context can be :CreateAppOnlyClientContextForSPHost(),CreateUserClientContextForSPHost()
I would have expected my provider app not to need any auth as its hosted via SharePoint
Ans : You can make IIS site [Hosting your provider hosted apps] to allow annonymous authentication.
You can get access token with this code.
var contextTokenString = TokenHelper.GetContextTokenFromRequest(Page.Request);
var appWeb = new Uri(clientContext.Web.Url);
if (contextTokenString != null)
{
SharePointContextToken contextToken =
TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
string accessToken =
TokenHelper.GetAccessToken(contextToken, appWeb.Authority).AccessToken;
}
Get current user :-
// Get current context to get load siteurl
var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
string webUrl =spContext.SPHostUrl.ToString();
//using (var clientContext = spContext.CreateUserClientContextForSPHost())
using (ClientContext clientContext = new ClientContext(webUrl))
{
clientContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
clientContext.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo(uName, pswd);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
// Load SP user from login name found from httpcontext
string currentSPUser = string.Concat("<<<FBADomainPrefix>>>",User.Identity.Name);
var currentUser = clientContext.Web.EnsureUser(currentSPUser);
clientContext.Load(currentUser);
clientContext.ExecuteQuery();
}

Related

Azure SQL authenticate as user via API with MS Identity Platform

I have an ASP.NET Core 3.1 Web App calling an ASP.NET Core 3.1 Web API, which in turn accesses an Azure SQL database. Authentication is provided via MSAL (Microsoft Identity Platform) - i.e. using the relatively new Microsoft.Identity.Web and Microsoft.Identity.Web.UI libraries.
The goal is to ensure that the user pulls data from SQL via the API under the context of his/her own login, thus enabling row-level security, access auditing and other good things.
I have succeeded in getting the sign-in process to work for the Web App - and through that it obtains a valid access token to access the API using a scope I created when registering the latter with AD.
When I run both the API and the App locally from Visual Studio everything works as expected - the correct access tokens are provided to the App to access the API, and the API to access SQL - in both cases under the user's (i.e. my) identity.
When I publish the API to App Services on Azure, however, and access it there either from a local version of the Web App or an App-Services hosted version of it, the access token that the API gets to access SQL contains the API's Application Identity (system-assigned managed identity), and not the user's identity. Although I can access SQL as the application, it's not what we need.
The Web App obtains its access token using the GetAccessTokenForUserAsync method of ITokenAcquisition - taking as a parameter the single scope I defined for the API.
The API gets its token (to access SQL) like so:
var token = await new AzureServiceTokenProvider().GetAccessTokenAsync("https://database.windows.net", _tenantId)
...where _tenantId is the tenant ID of the subscription.
I have added the SQL Azure Database "user_impersonation" API permission to the AD registration for the API - but that has not helped. As an aside, for some reason Azure gives the full name of this permission as https://sql.azuresynapse.usgovcloudapi.net/user_impersonation - which is slightly alarming as this is just a UK-based regular Azure account.
I have found a few similar posts to this, but mostly for older versions of the solution set. I'm hoping to avoid having to write my own code to post the token requests - this is supposed to be handled by the MSAL libraries.
Should I somehow be separately requesting a SQL access scope from the Web App after sign-in, or should the API be doing something different to get hold of a SQL access token that identifies the user? Why does it work perfectly when running locally?
It seems like this should be a very common use case (the most common?) but it is barely documented - most documentation I've found refers only to the application identity being used or doesn't tell you what to do for this particular tech stack.
Finally - success! In the end this was the critical piece of documentation: Microsoft identity platform and OAuth 2.0 On-Behalf-Of flow - the key points being:
The App only asks for a token to access the API.
The API then requests a token, on behalf of the user identified via the 1st token, to access SQL.
The key is that - since the API cannot trigger a consent window for the second step - I had to use the Enterprise Applications tab in the Azure portal to pre-grant the permissions for SQL.
So the good news is it does work: maybe it's obvious to some but IMO it took me far too long to find the answer to this. I will write up a fuller explanation of how to do this in due course as it can't only be me struggling with this one.
The bad news is that - in the course of my investigations - I found that Azure B2C (which is the next thing I need to add in) doesn't support this "On Behalf Of" flow - click here for details. That's a great shame as I think it's the most obvious use case for it! Oh well, back to the drawing board.
I'm currently working on a similar problem, using a Net5.0 Web app. The reason it appears to be working locally is you are signed into Visual Studio with a user who can access Azure SQL and those are the rights you get in the Db. The IDE is using those credentials in place of the Managed Service Identity, the latter gets used when you upload the app to Azure.
As you noted, in the App registration you need to grant permission to the App for Azure SQL Database user_impersonation.
In your code, you need to request a token from https://database.windows.net//.default (note the // as it's needed for v1 endpoints). By referencing /.default you are asking for all permissions you've selected for the app in the app registration portal.
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope
In Startup.cs you need to EnableTokenAcquisitionToCallDownstreamApi with the scope you require.
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi(new[]
{"https://database.windows.net//.default"})
// Adds the User and App InMemory Token Cache
.AddInMemoryTokenCaches();
services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the
// default policy
options.FallbackPolicy = options.DefaultPolicy;
});
services.AddDbContext<MyDatabaseContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("MyAzureConnection")));
// The database interface
services.AddScoped<ITodos, TodoData>();
services.AddRazorPages()
.AddRazorRuntimeCompilation()
.AddMvcOptions(o =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
o.Filters.Add(new AuthorizeFilter(policy));
})
.AddMicrosoftIdentityUI();
You also need to decorate your controllers with [AuthorizeForScopes(Scopes = new string[]{"https://database.windows.net//.default"}] and include the required scopes for that Controller. For Razor, it's at the top of the page model and requires a reference to `using Microsoft.Identity.Web;'
namespace ToDoApp.Pages.Todos
{
[AuthorizeForScopes(ScopeKeySection = "AzureSQL:BaseUrl")]
public class CreateModel : PageModel
I'm using a section in my appsettings.json for the scope and retrieving it using ScopeKeySection:
"AzureSQL": {
"BaseUrl": "https://database.windows.net//.default",
"Scopes": "user_impersonation"
}
This shows you where to include it for MVC, Razor and Blazor:
https://github.com/AzureAD/microsoft-identity-web/wiki/Managing-incremental-consent-and-conditional-access#in-mvc-controllers
Finally, your DbContext needs a token which you could pass to it from the client app (perhaps...).
This is how I am doing it at the moment
public class MyDatabaseContext : DbContext
{
private readonly ITokenAcquisition _tokenAcquisition;
public MyDatabaseContext (ITokenAcquisition tokenAcquisition,
DbContextOptions<MyDatabaseContext> options)
: base(options)
{
_tokenAcquisition = tokenAcquisition;
string[] scopes = new[]{"https://database.windows.net//.default"};
var result = _tokenAcquisition.GetAuthenticationResultForUserAsync(scopes)
.GetAwaiter()
.GetResult();
token = result.AccessToken;
var connection = (SqlConnection)Database.GetDbConnection();
connection.AccessToken = result.token;
}
This is a flawed solution. If I restart the app and try to access it again I get an error Microsoft.Identity.Web.MicrosoftIdentityWebChallengeUserException: IDW10502: An MsalUiRequiredException was thrown due to a challenge for the user
It seems to be related to the TokenCache. If I sign out and in again or clear my browser cache the error is resolved. I've a workaround that signs the app in on failure, but it's deficient since I'm using the app's credentials.
However, it successfully connects to the Azure SQL Db as the user instead of the App with the user's rights instead. When I do solve the error (or find one) I will update this answer.

Pass Logic App credential to custom SharePoint Client C# Function App SharePoint

I have created logic apps in Azure that uses my credential to connect to our SharePoint Online sites and then run without me being around. I want to perform more complex operations on the SharePoint sites and would prefer to create a C# Function App. However I cannot see a way to pass my credentials to the Microsoft.SharePoint.Client without my having to be there to authenticate. I have researched using a certificate but that requires admin approval which I cannot get. Is there a way for me to use the existing SharePoint Logic App connection, which has my credential information, and pass that to a custom Function App? Here's a quick image of how the connection looks in the Logic App. Instead of using the built in Azure action, I want to replace it with my custom Function App passing that connection to the function app.
Then I would need use that to somehow create the ClientContext:
var ctx = new ClientContext(siteUrl);
ctx.ExecutingWebRequest += (s, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + authenticationResult.AccessToken;
};
return ctx;
Which could then be used against the SharePoint site:
using (ClientContext ctx = await csomHelper.GetClientContext(siteUrl))
{
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
log.LogInformation($"found site : {web.Title}");
}
While I believe there is no way to fetch the access token from an existing connection, you could expose your function app as a custom connector for use in logic apps.
Firstly, you would need an Azure AD app registration with appropriate permissions to sharepoint.
Then, while creating the custom connector, the security config should be Generic OAuth 2.0 with appropriate details of the Azure AD you created earlier.
And you can then use the custom connector in your logic app, which will trigger an OAuth flow similar to other connectors.
There is an official doc for creating a custom connector for an Azure AD protected Azure Function which is pretty similar and something that you can refer.

Windows Auth with Microsoft.Owin.Testing.TestServer

I have a Web API application which I'm protecting with Windows Authentication (locally, it'll translate to AD in the production environment). I just started adding features that rely on authentication and/or getting properties of the current user, and I immediately fell on a road block: the testing server doesn't seem able to authenticate.
How can I make the following test code send an authenticated request using Windows Authentication?
using (var server = Microsoft.Owin.Testing.TestServer.Create(MyApp.Startup.Configure)) {
var response = server.HttpClient.GetAsync(url).Result;
// Assert things about the response
}

Dynamics CRM - Caller not authenticated to service

I have an MVC4 Web Application on Web Server A that is consuming the Dynamics CRM Web Service using the OrganizationServiceProxy, which is on Web Server B. The MVC4 application is setup with ASP .NET Impersonation and Windows Authentication enabled. When I call the WhoAmI I get an error:
'The caller was not authenticated by the service.'
Now if I move the MVC4 Application to Web Server B (same as CRM) with the same Authentication as it had on Web Server A it calls WhoAmI without an exception.
Here is the code being used to connect to the server.
string serviceURL = ConfigurationManager.AppSettings["CRMROOTURL"].ToString() + "XRMServices/2011/Organization.svc";
this.CRMService = GetCRMService(serviceURL);
private OrganizationServiceProxy GetCRMService(string serviceURL)
{
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
OrganizationServiceProxy client
= new OrganizationServiceProxy(new Uri(serviceURL), null, credentials, null);
return client;
}
Here is a screenshot of the authentication on the IIS Web Site.
Per the correct answer I just wanted to provide some snippets to help anyone else.
string loggedUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = new NetworkCredential(username, password, domain);
OrganizationServiceProxy client
= new OrganizationServiceProxy(new Uri(serviceURL), null, credentials, null);
client.ClientCredentials.Windows.ClientCredential = credentials.Windows.ClientCredential;
// -- Retrieve the user.
QueryExpression expression = new QueryExpression
{
EntityName = "systemuser",
ColumnSet = new ColumnSet("systemuserid")
};
expression.Criteria.AddCondition("domainname", ConditionOperator.Equal, loggedUser);
EntityCollection ec = client.RetrieveMultiple(expression);
if (ec.Entities.Count > 0)
{
// -- Impersonate the logged in user.
client.CallerId = ec.Entities[0].Id;
}
Thanks!
Unless you explicitly state otherwise (and without any code to see how you are creating your OrganizationServiceProxy), on premise OrganizationServiceProxies will use the current AD account (of the service account, not the user's specific account) to connect to CRM. I'm guessing that the App pool you're running on Server A isn't a CRM user, and the one on Server B is. If so, either change Server A's user to be the same user as Server B, or make the Server A's user a user in CRM.
Edit
You're using the default network credentials to connect to CRM. This mean that no matter what IIS authentication you are using, you will connect to CRM as the App Pool User Account. This works as long as the App Pool user is a CRM user, but is probably not what you want.
You can set the network credential manually using this method:
creds.Windows.ClientCredential = new System.Net.NetworkCredential("UserId", "Password", "DomainName");
Then get the ASP.Net User's domain name and use impersonation to connect to CRM to ensure that all of the security for that individual is correctly applied.
Something stupid - be careful you aren't escaping your user name!
creds.Windows.ClientCredential = new NetworkCredential("domain\user", "PASSWORD");
Notice that the \u is an escape sequence - you need to type "domain\user".

Call a web-service under current user credentials

I have a custom WCF web-service confugured with windows authentication and a WPF client application that needs to call the former. The service checks the username and pull some specific data from a database. So I have to call the service using credentials of the user running the application.
The problem is my service is hosted under another site with windows authentication and users can authenticate there with another accounts. Windows (or IE?) caches last accout used and then my client app uses it too!
Example:
I enter the website under "MYDOMAIN\AdminUser"
I run following code (from the client app, it's not web code)
var client = new TestServiceClient();
var currentUser = WindowsIdentity.GetCurrent(); // just informative field nothing more, i don't use it anyhow
// currentUser.Name = "MYDOMAIN\\MyUserName" - it's current value, i'm not trying to set it
client.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
var data = client.GetTestData();
Service gets called by "MYDOMAIN\AdminUser"..
I know I can create NetworkCredential with name and password but I then will have to store it somewhere, encript it and so on..
To clarify the problem: client process running under one account calls the service under another account by itself, just becouse windows supplies the call with another credentials under the hood.