User Assigned Identities with App Service and Azure SQL does that work? - azure-managed-identity

I am trying to get App Service to connect with Azure Sql database. I can git is nicely work with System Assigned Identities with the same code, but I prefer to use User Assigned Identities (UAI), but I cannot get it work.
Steps which I do:
Created a UAI via the portal, name of the UAI "uai-dev-appname-001"
At the Identity tab of the Azure App Service I selected 'User Assigned Identity' and selected the UAI made in the previous step.
Ran the following SQL CMD
CREATE USER [uai-dev-appname-001] FROM EXTERNAL PROVIDER
ALTER ROLE db_datareader ADD MEMBER [uai-dev-appname-001]
ALTER ROLE db_datawriter ADD MEMBER [uai-dev-appname-001]
Set Connectionstring in the ASP.NET to:
Data Source=sqlsrv-name-dev-001.database.windows.net; Initial Catalog=sqldb-name-dev-001;
Using the following code in mine ASP.NET Core:
SqlConnection connection = new SqlConnection
{
ConnectionString = configuration.GetConnectionString("nameDatabase")
};
AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
var token = provider.GetAccessTokenAsync("https://database.windows.net/").Result;
connection.AccessToken = token;
Deploy to Azure App Service and watched the URL. The result is: error 500.30
Looking in the Application Event Log:
Unhandled exception. System.AggregateException: One or more errors occurred. (Parameters: Connection String: [No connection string specified], Resource: https://database.windows.net, Authority: . Exception Message: Tried the following 3 methods to get an access token, but none of them worked.
Parameters: Connection String: [No connection string specified], Resource: https://database.windows.net, Authority: . Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. Received a non-retryable error. MSI ResponseCode: BadRequest, Response: {"StatusCode":400,"Message":"No MSI found for specified ClientId/ResourceId.","CorrelationId":"a68bf757-518a-42e1-85a9-342320d39b5a"}
Parameters: Connection String: [No connection string specified], Resource: https://database.windows.net, Authority: . Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. Visual Studio Token provider file not found at "D:\local\LocalAppData.IdentityService\AzureServiceAuth\tokenprovider.json"
Parameters: Connection String: [No connection string specified], Resource: https://database.windows.net, Authority: . Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. 'az' is not recognized as an internal or external command,
operable program or batch file.
The most interesting part in IMO is:
Response: {"StatusCode":400,"Message":"No MSI found for specified ClientId/ResourceId.","CorrelationId":"a68bf757-518a-42e1-85a9-342320d39b5a"}
Mine question are:
Does User Assigned Identies work with Azure SQL?
If so what do I do wrong?
Does someone has a working example.

User-assigned Managed Identity is supported from version 1.2.1 of Microsoft.Azure.Services.AppAuthentication.
So, please update the version of Microsoft.Azure.Services.AppAuthentication to the latest.
Then set AzureServicesAuthConnectionString in the Appsettings of the AppService to RunAs=App;AppId={ClientId of user-assigned identity}
E.g.
RunAs=App;AppId=587f16c8-81ed-41c7-b19a-9ded0dbe2ca2
Documentation can be found here.
Once you do these steps, your code should be using user-assigned managed identity.

Related

(UPDATED) Published blazor wasm app fails to connect to Postgresql

Update 2: this solved the issue for me: https://dba.stackexchange.com/questions/83984/connect-to-postgresql-server-fatal-no-pg-hba-conf-entry-for-host
Also had to make sure I added an https address in the Urls entry in appsettings.json
Update: if checked Postgres logs and found this:
2022-05-09 21:57:59.816 PKT [11284] FATAL: password authentication failed for user "safzal"
2022-05-09 21:57:59.816 PKT [11284] DETAIL: Role "safzal" does not exist.
Connection matched pg_hba.conf line 89: "host all all ::1/128 scram-sha-256"
"safzal" is my PC username but not the username I configured in connection string. Why isn't dotnet using my connection string?
I am making a Blazor wasm (hosted) app with Postgres db. During development, I put connection string without mentioning userid or password in appSettings.json. I used user secrets to store userid and password and linked them in Program.cs. This approach worked fine, I was able to use dotnet ef migrations add myMigration and dotnet ef database update. I was able to use the app normally during development.
However, when I publish, I cannot get the db connection to work. The app loads fine but as soon as I attempt data access it shows "An unhandled error has occured." with option to Reload.
I get the following http 500 internal server error error in browser console:
I was initially using IIS to attempt to run the app. When I tried to run it via Kestrel it shows this error:
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database 'fistepsdb' on server ''.
fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred while iterating over the results of a query for context type 'fisteps.Server.Data.AppDbContext'.
Npgsql.NpgsqlException (0x80004005): No password has been provided but the backend requires one (in SASL/SCRAM-SHA-256)
I have already tried:
Putting userId and password directly in connection string
Putting connection string in VS2022 Publish dialog > Show all settings > Settings > Databases > [Password, PostgreSqlConnection, UserId]
Putting connection string in IIS > Sites > Default Web Site > Management > Configuration Editor > Section: connectionStrings (though I am unsure about providerName here).
Any help would be most appreciated.

Wso2 admin/admin failing after changing to mysql datasource

I was facing issue while login to Carbon Management Console
Version; WSO2 IS 5.10. 0 as Key Manager
Changes:
I have made Mysql database changes for WSO2AM_DB, WSO2Shared_DB,WSO2User_db in deployment.toml file.
When i tried login Management Console with default admin/admin credentials, I am getting error in UI:
Login failed! Please recheck the username and password and try again.
ERROR {org.wso2.carbon.core.services.authentication.AuthenticationAdmin} - System error while Authenticating/Authorizing User : com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
Also user store changes in deployment.toml cause error
Changes:
[user_store]
type = "database"
[user_store.properties]
TenantManager="org.wso2.carbon.user.core.tenant.JDBCTenantManager"
ReadOnly=false
ReadGroups=true
WriteGroups=true
scim_enabled = true
[realm_manager]
data_source = "WSO2USER_DB"
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure normally means the configured database is not accessible.
Did you define the database.user configuration in the deployment.toml according to WSO2 jdbc user configuration guidelines? If this is already configured, check the configured connection url and network connectivity from WSO2-IS to userstore database.

Exception using Azure Managed Service Identity across tenants

I'm building an Azure web app for a client that will be provisioned into many other directories for their customers. This app will call a web API in my client's directory, which will then call back to another web API in the customer's directory. Something like this:
Other Customer AAD1 --------- My client AAD2
App --------------------------------> Web API 2
Web API 1 <-------------------------- Web API 2
We have been able to get the first call to work. This requires a corresponding App Registation for Web API 2 in AAD1. We figure that we could get the callback to work by following the same pattern, with a registration for Web API1 in AAD2. However, that might be a LOT of these 'proxy' registration in my client's AAD, so we're looking at alternatives.
We are exploring using Managed Service Identity, which we think will allow us to get tokens that are valid for resources in other tenants. If there's a better way, I'm certainly interested in knowing about it.
I've followed the code example from here using the Microsoft.Azure.Services.AppAuthentication library: https://learn.microsoft.com/en-us/azure/app-service/app-service-managed-service-identity#obtaining-tokens-for-azure-resources
// In Web API 2
using Microsoft.Azure.Services.AppAuthentication;
// ...
var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(
"https://<App ID URI for Web API1>");
Web API2 is configured to have a Managed Service Identity.
I'm currently running this on my local machine, and I've installed Azure CLI and I'm logged in. I've tried 'az account get-access-token', and I get a valid token.
When Web API2 tries to get the token to be able to call Web API1, I get an exception:
Parameters: Connectionstring: [No connection string specified], Resource: , Authority: . Exception Message: Tried the following 2 methods to get an access token, but none of them worked.
Parameters: Connectionstring: [No connection string specified], Resource: , Authority: . Exception Message: Tried to get token using Managed Service Identity. Unable to connect to the Managed Service Identity (MSI) endpoint. Please check that you are running on an Azure resource that has MSI setup.
Parameters: Connectionstring: [No connection string specified], Resource: , Authority: . Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. ERROR: Get Token request returned http error: 400 and server response: {"error":"invalid_grant","error_description":"AADSTS65001: The user or administrator has not consented to use the application with ID '04b07795-8ddb-461a-bbee-02f9e1bf7b46' named 'Web API 1'. Send an interactive authorization request for this user and resource.\r\nTrace ID: f5bb0d4d-6f92-4fdd-81b7-e82a78720a00\r\nCorrelation ID: 04f92114-8d9d-40c6-b292-965168d6a919\r\nTimestamp: 2017-10-19 16:39:22Z","error_codes":[65001],"timestamp":"2017-10-19 16:39:22Z","trace_id":"f5bb0d4d-6f92-4fdd-81b7-e82a78720a00","correlation_id":"04f92114-8d9d-40c6-b292-965168d6a919"}
What's interesting is that there's no application with ID '04b07795-8ddb-461a-bbee-02f9e1bf7b46' in either AAD1 or AAD2. Is this a known Azure app? I thought that it might be the Service Management API, but I'm not sure.
In any case, I'm not sure of the proper way to grant permission. I've tried building different content URLs like this into my browser, but none of them seem to have done the trick:
https://login.microsoftonline.com/(AAD1 ID)/adminconsent
?client_id=(App ID)
&redirect_uri=https://localhost:44341
&resource=(App ID URI for Web API1)
&prompt=admin_consent
https://login.microsoftonline.com/(AAD1 ID)/adminconsent
?client_id=04b07795-8ddb-461a-bbee-02f9e1bf7b46
&redirect_uri=https://localhost:44341
&resource=(App ID URI for Web API1)
&prompt=admin_consent
(This last one tells me that the reply URL is incorrect; since it's not one of my apps, I can't find the reply URL)
Note that the tenant is AAD1.
Am I missing something, or am I not using this feature correctly?
Thanks in advance.
AzureServiceTokenProvider uses Azure CLI (among other options) for local development. For a scenario where a service calls an Azure Service, this works using the developer identity from Azure CLI, since Azure services allow access to both users and applications.
For a scenario where a service calls another custom service (like your scenario), you need to use a service principal for local development. For this, you have two options:
Login to Azure CLI using a service principal.
First, create a service principal for local development
https://learn.microsoft.com/en-us/cli/azure/create-an-azure-service-principal-azure-cli?view=azure-cli-latest
Then login to Azure CLI using it.
az login --service-principal -u 25922285-eab9-4262-ba61-8083533a929b --password <<pwd>> --tenant 72f988bf-86f1-41af-91ab-2d7cd011db47 --allow-no-subscriptions
Use the --allow-no-subscriptions argument since this service principal may not have access to any subscription.
Now, AzureServiceTokenProvider will get a token using this service principal for local development.
Specify service principal details in an environment variable. AzureServiceTokenProvider will use the specified service principal for local development. Please see the section Running the application using a service principal in local development environment in this sample on how to do that. https://github.com/Azure-Samples/app-service-msi-keyvault-dotnet
Note: Ths is only for local development. AzureServiceTokenProvider will use MSI when deployed to App Service.

Realm Authentication Server Error with iCloud Auth

RealmSwift 2.8.3, Realm Object Server 1.8.1, Xcode 8, Swift 3.1
I can get pretty much everything with the Realm Object Server (ROS) to work with iCloud authentication, but I'm running into an issue when I have a new user authenticate that doesn't yet have an account on my ROS instance.
I'm successfully able to retrieve their iCloud token, but user is nil when I do this:
let credentials = SyncCredentials.cloudKit(token: token)
SyncUser.logIn(with: credentials, server: serverURL) { user, error in
DispatchQueue.main.async{
if user == nil {
//--- Error ---
//This is where I end up. I can see the token in the log but no user object
}else{
//--- Success ---
}
}
}
When I check the error log in my ROS (running on Ubuntu), I get this internal server error (500):
2017-07-12T00:39:39.170Z - warn: auth.cloudkit: Handle request failed with: Error: Request failed with code AUTHENTICATION_FAILED: Authentication failed.
2017-07-12T00:39:39.174Z - warn: [services] internal error: Error: Request failed with code AUTHENTICATION_FAILED: Authentication failed.
at request.catch.err (/usr/lib/nodejs/realm-object-server-developer/.build/src/node/managers/auth/provider/cloudkit.js:131:23)
at process._tickCallback (internal/process/next_tick.js:109:7).
Now just to make sure, I assume that SyncCredentials.cloudKit(token: token) creates a user if that token isn't found on my server and returns a new user object. I don't see anything in the docs about creating a new user vs. authenticating an existing one.
UPDATE
I double-checked all my connections to iCloud, made sure my key_id found in my configuration.yml file is right and that my key matches what I have in my iCloud container.
Now I get a different error. :)
2017-07-12T01:12:54.801Z - warn: auth.cloudkit: Handle request failed with: TypeError: Cannot read property 'reason' of undefined
2017-07-12T01:12:54.809Z - warn: [services] internal error: TypeError: Cannot read property 'reason' of undefined
at signedRequest.then.catch.err (/usr/lib/nodejs/realm-object-server-developer/.build/src/node/managers/auth/provider/cloudkit.js:86:11)
at process._tickCallback (internal/process/next_tick.js:109:7).
According to the docs, account should be created if not existed before
If the credentials are valid, the user is granted access to Realm
Object Server. A new user account is created if the credentials are
not coupled to an existing account.
I guess it's problem with private_key_path in configuration.yml. Try to move .pem file to another location and see if there are any changes.
Also, remember to restart the server after changing the configuration file.

The AWS Access Key Id needs a subscription for the service : AmazonSNS; Status Code: 403; Error Code: OptInRequired

I am creating Platform Application for that I am providing following details:
Application Name = "TestNotification"
Push Application Platform = Apple Development
Push Certificate Type = iOS Push Certificate
Choosing P12 file
Loading Credential from file
Certificate Key
Private Key
And Finally Clicking on Create Platform Application
But I am getting following error:
The AWS Access Key Id needs a subscription for the service (Service: AmazonSNS; Status Code: 403; Error Code: OptInRequired; Request ID: a0b89f4e-f34b-51f2-b4ae-ce136d8b1fe1).
I google out but not able to solve the issue.. Please help.
In my case, Account verification was not completed.
complete the account registrations or varication process by going to
https://portal.aws.amazon.com/billing/signup?type=resubscribe#/resubscribed.

Resources