Assign service principal Admin Role on Service Fabric AD App - azure-service-fabric

I am setting up Azure AD applications for my Service Fabric cluster, so I do not need to rely on Cert Auth to connect to the cluster.
We use a Service Principal from an App Registration that has Contributor access to the subscription to run the ARM template to set up the cluster. Is there a way that I can make the Service Principal an Admin on the Cluster AD Application as well?
Our deployment script is in Powershell and saw this post: Deploying ServiceFabric apps using AzureAD Authentication on how to automate connecting, but I need a way to connect with a Service Principal.

I believe you could do it by translating this C# code into Powershell, e.g by using New-Object to create the objects mentioned below.
Make sure to replace the guids with your own AppRegistation details, the thumbprint of the server certificate, and the cluster url.
string tenantId = "C15CFCEA-02C1-40DC-8466-FBD0EE0B05D2";
string clientApplicationId = "118473C2-7619-46E3-A8E4-6DA8D5F56E12";
string webApplicationId = "53E6948C-0897-4DA6-B26A-EE2A38A690B4";
string token = GetAccessToken(
tenantId,
webApplicationId,
clientApplicationId,
"urn:ietf:wg:oauth:2.0:oob");
string serverCertThumb = "A8136758F4AB8962AF2BF3F27921BE1DF67F4326";
string connection = "clustername.westus.cloudapp.azure.com:19000";
var claimsCredentials = new ClaimsCredentials();
claimsCredentials.ServerThumbprints.Add(serverCertThumb);
claimsCredentials.LocalClaims = token;
var fc = new FabricClient(claimsCredentials, connection);
try
{
var ret = fc.ClusterManager.GetClusterManifestAsync().Result;
Console.WriteLine(ret.ToString());
}
catch (Exception e)
{
Console.WriteLine("Connect failed: {0}", e.Message);
}
...
static string GetAccessToken(
string tenantId,
string resource,
string clientId,
string redirectUri)
{
string authorityFormat = #"https://login.microsoftonline.com/{0}";
string authority = string.Format(CultureInfo.InvariantCulture, authorityFormat, tenantId);
var authContext = new AuthenticationContext(authority);
var authResult = authContext.AcquireToken(
resource,
clientId,
new UserCredential("TestAdmin#clustenametenant.onmicrosoft.com", "TestPassword"));
return authResult.AccessToken;
}
They get an access token from Azure AD using the implicit flow (which needs to be enabled in your AppRegistration). And they use it in the ClaimsCredential to pass into FabricClient.
More info here.

I figured out how to get it to work.
The first part is to give the service principal the role on the Client App.
Go to Azure Portal -> Azure Active Directory -> App Registrations and select the Client app created.
Go to the Manifest page and find the Admin app role and add an entry for "Application" to the allowedMemberTypes property. Save when updated.
Go to App Registrations and select the app you are using to run automation with
Go to API Permissions, Click Add permission Button. Go to the APIs my organization uses tab and search for the SF Cluster Client Application.
Select Application Permissions and chose the Admin permission.
Hit the Grant admin consent for <Tenant Name>
Once permission is granted, you can run the PowerShell script:
Add-Type -Path "./Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$authority = "https://login.microsoftonline.com/$($tenantId)"
$credentials = [Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential]::new($AzureLogin, $AzurePassword)
$authContext = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]::new($authority)
$authResult = $authContext.AcquireTokenAsync($clientAppId, $credentials)
$Token = $authResult.Result.AccessToken
Connect-ServiceFabricCluster -AzureActiveDirectory -SecurityToken $Token `
-ConnectionEndpoint $endpoint -ServerCertThumbprint $thumbprint

Related

How to add policy to Keycloak - UI crashes

I'm trying to enable flow when some admin user by some admin client is able to create users and obtain their access tokens to be used for another clients.
I have KeyCloak setup with token exchange and fine grained authz enabled and configured clients. I'm able to login my admin user by REST api, then exchange token. But when I specify audience I got error.
This one returns token but I need token for another client/audience.
http -f POST https://my-keycloak-server.com/auth/admin/realms/my-realm/protocol/openid-connect/token grant_type=urn:ietf:params:oauth:grant-type:token-exchange requested_subject=1a147915-53fe-454d-906a-186fecfa6974 client_id=api-admin client_secret=23a4ecbe-a9e8-448c-b36a-a45fa1082e6e subject_token=eyJhbGeiOiJSUzI1NiIs......
This one is failing with error.
http -f POST https://my-keycloak-server.com/auth/admin/realms/my-realm/protocol/openid-connect/token grant_type=urn:ietf:params:oauth:grant-type:token-exchange requested_subject=1a147915-53fe-454d-906a-186fecfa6974 client_id=api-admin client_secret=23a4ecbe-a9e8-448c-b36a-a45fa1082e6e subject_token=eyJhbGeiOiJSUzI1NiIs...... audience=my-another-client
{
"error": "access_denied",
"error_description": "Client not allowed to exchange"
}
So I tried to setup fine grained auth for target audience client (enabled it in tab, then tried to add policy for my admin user to be able to exchange token) but when I want to add policy that will allow my admin user to perform token exchange I'm stuck on UI error.
When typing policy name I got 404 when Keycloak is looking for name colisions. Afaik 404 in this case shouldn't block form from posting because it is no name collision. Instead I got instantly redirected with error.
https://my-keycloak-server.com/auth/admin/realms/my-realm/clients/1bafa9a4-f7e2-422c-9188-58ea95db32ef/authz/resource-server/policy/search?name=some-name
In the end of the day I can't add any policy in Keycloak. All the time form validation is ending up with crash caused by 404 policy name not found.
I'm using dockerized keycloak 10.0.0
Any ideas?
I hacked it by live editing Angular JS UI script function that performs verification in line 2403.
this.checkNameAvailability = function (onSuccess) {
if (!$scope.policy.name || $scope.policy.name.trim().length == 0) {
return;
}
ResourceServerPolicy.search({
realm: $route.current.params.realm,
client: client.id,
name: $scope.policy.name
}, function(data) {
if (data && data.id && data.id != $scope.policy.id) {
Notifications.error("Name already in use by another policy or permission, please choose another one.");
} else {
onSuccess();
}
});
}
to
this.checkNameAvailability = function (onSuccess) {
onSuccess();
}
And that end up with successfuly added policy. Still looks like it's UI bug.

403 Forbidden error while accessing Azure web api using certificate authentication

I am getting 403 Forbidden exception while accessing simple azure webapi with certificate authentication, only while accessing from asp.net web application. I am using WebClient inherited object to overide GetWebRequest to add client certificate.
public class CertificateWebClient : WebClient
{
private readonly X509Certificate2 certificate;
public CertificateWebClient(X509Certificate2 cert)
{
certificate = cert;
}
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
request.ClientCertificates.Add(certificate);
return request;
}
}
And I am using the object CertificateWebClient DownloadString function to access the web api.
X509Certificate2 newCertificate = new X509Certificate2("bytearray");
CertificateWebClient webClient = new CertificateWebClient(newCertificate)
{
Proxy = new WebProxy("proxy address")
};
var result = webClient.DownloadString("https://webapiaddress/api/Values");
I am accessing the web api in the similar manner in windows forms and it works absolutely fine.
I could resolve this issue by storing and retrieving the certificate from Azure key vault in Base 64 string format. Using Convert.ToBase64String("raw certificate data") and Convert.FromBase64String("base64 cert string"), so I had to modify the above code as
X509Certificate2 newCertificate = new X509Certificate2(Convert.FromBase64String("base64 cert string"));
Only base 64 format keeps the certificate raw data intact while Adding/Retrieving certificate data to azure key vault.
The Certificate should have been ideally added to Azure key vault certificate store but the project requirement was to store it as key.

invalid Client for exchange code _ identityserver3 _ AppAuth

I'm using AppAuth framework for authentication in my Swift app, I can login but after login and coming back to my app, I can't exchange the code and get error invalid client.
My client configuration is:
var client = new Client
{
ClientId = "IOS.Client",
ClientName = "IOS Client",
RedirectUris = { "com.mysite.accounts:/oauthredirect" },
AllowedGrantTypes = GrantTypes.Code, //AuthorizationCode
AllowedScopes = { "openid", "profile", "offline_access" },
};
I set ClientSecret (SHA-256) and my ClientId is ok but I get error invalid client.
I checked my logs and there is an error: secret validators could not validate secret
what's wrong?
IIRC in IS3 you had to set a client secret. We didn't allow empty ones.
Either you set a secret on client and server, or upgrade to IS4 - IS3 is deprecated since quite some time.
When using IdentityServer3 and AppAuth you should not use special characters in ClientSecret and set your grant AuthorizationCodeWithProofKey.
this link is useful

ASP double hop request in kerberos delegation scenario

Please help!
I need my asp application to request remote systems with credentials of impersonated user. But always get 401 Unauthorized errors.
I made all configurations from here: https://support.microsoft.com/en-us/help/810572/how-to-configure-an-asp-net-application-for-a-delegation-scenario
Kerberos is configured and working in my app and my test remote app(i see kerberos tickets in fiddler). Delegation, spns and everything is configured.
Thats my code usnig System.Net.Http.httpclient:
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true,
PreAuthenticate = true
};
using (HttpClient client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Clear();
var method = new HttpMethod("GET");
var request = new HttpRequestMessage(method, "http://testdelegationapp.avp.ru/");
var response = client.SendAsync(request).Result;
}
In fact http request is made by Apppool account (I get 401 error when restricting access to Apppool account in remote app IIS)
Here: How to get HttpClient to pass credentials along with the request?
is claimed that HttpClient cant pass security token to another thread, and its better to use synchronous methods of System.Net.WebClient
Code using webclient:
var wi = (WindowsIdentity)HttpContext.User.Identity;
var wic = wi.Impersonate();
try
{
string URI = "http://testdelegationapp.avp.ru/";
using (WebClient wc = new WebClient())
{
wc.UseDefaultCredentials = true;
string response = wc.DownloadString(URI);
}
}
finally
{
wic.Undo();
}
Result is even worse, the same 401 error, but in fiddler i can see that webclient using NTLM ticket to get to remote app!
Configuring of flowing tokens throw threads from here :Unable to authenticate to ASP.NET Web Api service with HttpClient
doesnt help either. SecurityContext.IsWindowsIdentityFlowSuppressed() is false.
WindowsIdentity.GetCurrent().Name and Thread.CurrentPrincipal.Identity.Name shows impersonated user as it should be.
All that time problem was in chrome browser, by default it prohobits kerberos delegation. You shoud add the following to registry:
Path: HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome ;
string: AuthNegotiateDelegateWhitelist ;
value: *.avp.ru
So, now my working configuration is
HttpClient for web requests.
ASP impersonation ON in IIS if you want to execute all your app under
delegated credentials. If you want method specific delegation, then use:
var wi = (WindowsIdentity)HttpContext.User.Identity;
var wic = wi.Impersonate();
wic.Undo();
HttpClient executes request in another thread , so in aspnet_config.config we need following changes:
<legacyImpersonationPolicy enabled="false"/>
<alwaysFlowImpersonationPolicy enabled="true"/>
You can find aspnet_config.config in:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet.config
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\aspnet.config
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet.config

Drupal services API returns "access denied for user anonymous" with xcode basic auth

I have basic auth setup and working with Drupal services, and am using the administrator login. It is returning data for a voting API. When I access the site (with login) it retrieves the details. But on my xcode project, when I query the API as a get command (using services definition http://example.site/ios1/user/{UID} ) it returns following error.
"access denied for user anonymous".
Any tips?
Solved. I had to select 'http basic authentication' in Drupal services, add 'headers' to the alamofire query, plus my authentication header needed to e:
let user = "example"
let password = "example"
let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]