We are trying to connect and insert data into our AZURE SQL DB using sqlalchemy and pandas.dataframe.to_sql using our service principal and token. The problem is that we are able to connect to one database perfectly but to another database we are getting the following error
sqlalchemy.exc.InterfaceError: (pyodbc.InterfaceError) ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user '<token-identified principal>'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user '<token-identified principal>'. (18456)") (Background on this error at: https://sqlalche.me/e/14/rvf5)
We are trying to login via Service Principal using client id, client secret & Tenant ID. All the values have been verified and are working fine to connect to the database using Azure databricks.
Any help would be highly appreciated.
The problem is that we are able to connect to one database perfectly but to another database, we are getting the Login failed for user '<token-identified principal>' error.
According to documentation, if you are using any external provider then you need to create and map the required permissions to Azure AD identities.
CREATE USER <Azure_AD_principal_name> FROM EXTERNAL PROVIDER;
CREATE USER [bob#contoso.com] FROM EXTERNAL PROVIDER;
CREATE USER [alice#fabrikam.onmicrosoft.com] FROM EXTERNAL PROVIDER;
And after that, as suggested by Jason Pan , make sure to On Identity status on portal.
Updated answer:
According to Radiatelabs, the issue got fixed after copying the whole database from DEV to UAT and creating the UAT user in the database.
References: Login Failed for user ``, Login failed for user token-identified principal when web app is in an AAD Group ,and Login failed for user 'token-identified principal' but works in Data Studio
Related
I'm using SQL Server 2019 and try to connect to a Oracle DB via Polybase:
CREATE DATABASE SCOPED CREDENTIAL OracleUser WITH IDENTITY = 'username', Secret = 'password';
CREATE EXTERNAL DATA SOURCE [OrDB] WITH (LOCATION = N'oracle://192.168.1.5:1521'),
CREDENTIAL = OracleUser);
I'm getting the error:
Login failed. The login is from an untrusted domain and cannot be used with Integrated authentication.
However the user is not a domain user and oracle does not use integrated authentication.
As I mentioned in my comment above, you get this error if you are logged into your SQL Server instance with integrated security. This is due to a regression bug in SQL Server 2019.
Log in with SQL authentication instead, and it will work.
try this:
CREATE EXTERNAL DATA SOURCE [OrDB] WITH (LOCATION = N'oracle://192.168.1.5:1521'),
CREDENTIAL = OracleUser,
CONNECTION_OPTIONS = 'UseDefaultEncryptionOptions=false'
);
An on-premise web application (.net 4.6.1) which uses Windows Authentication for its users and then AD Integrated Authentication to connect to a MS SQL database is been migrated to Azure.
Ideally, the existing security mechanism of granting permissions to AD users on database objects and let the DB be security source of the application should be kept.
A copy of the SQL database has already been created and configured.
If I run the web application locally but using the new Azure database everything works as expected.
If I run this command I get the expected AD user:
SELECT CURRENT_USER;
Now, when I deploy exactly the same application to an Azure App Service and enable Azure Active Directory Authentication and Managed Service Identity, the user is authenticated correctly on the Web application but it is not able to connect to the SQL database and the following error is returned:
Errors = System.Data.SqlClient.SqlErrorCollection ClientConnectionId =
e9f0c48a-3159-465c-ab72-c1da99761b8f Class = 14 LineNumber = 65536
Number = 18456 Procedure = Server =
xxxxxxxxxxx.tr4.canadacentral1-a.worker.database.windows.net,11057
State = 1 Source = .Net SqlClient Data Provider ErrorCode =
-2146232060 Message = Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
If I disable Managed Service Identity, I get this error instead:
InnerExceptions =
System.Collections.ObjectModel.ReadOnlyCollection`1[System.Exception]
Message = One or more errors occurred. Data =
System.Collections.ListDictionaryInternal InnerException =
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException:
Parameters: Connection String: [No connection string specified],
Resource: https://database.windows.net/, Authority: . Exception
Message: Tried the following 4 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. 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: 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. Parameters: Connection String: [No
connection string specified], Resource: https://database.windows.net/,
Authority: https://login.microsoftonline.com/common. Exception
Message: Tried to get token using Active Directory Integrated
Authentication. Access token could not be acquired.
get_user_name_failed: Failed to get user nameInner Exception : The
format of the specified domain name is invalidat
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.d__14.MoveNext()
Is it what I'm trying to do possible? If yes, what am I missing? Any thoughts will be appreciated.
For reference, this is the method returning the SQL connection:
private SqlConnection GetSqlConnection()
{
var accessToken = new AzureServiceTokenProvider().GetAccessTokenAsync("https://database.windows.net/").Result;
return new SqlConnection
{
ConnectionString = WebConfigurationManager.ConnectionStrings["Default"].ConnectionString,
AccessToken = accessToken
};
}
... and this is the connection string:
<connectionStrings>
<add name="Default" connectionString="Data Source=myserver.database.windows.net;Initial Catalog=MyDB;" providerName="System.Data.SqlClient" />
</connectionStrings>
Note: The local AD is been synchronized with its Azure AD counterpart.
I think to solve your issue you have to do the following:
Grant access for the user as external provider in the database: (you can also find in AAD, under Enterprise applications when you select All applications). Important to make sure, that app service identity is already created at this moment.
For a web app it is the name of the web app
If you are using deployment slots the sql user name is {application-name}/slots/{slot-name}
If you are using User managed identity, you also have to specify app setting AzureServicesAuthConnectionString with the following value: RunAs=App;AppId={ClientId of identity}
Change your connection string and web config to use the interactive authentication.
Connection string can be something like this: Server=tcp:{server}.database.windows.net,1433;Initial Catalog={DatabaseName};Persist Security Info=False;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Authentication='Active Directory Interactive'.
This also works with EntityFramework, but if you set up connection string directly in Azure you need to choose Custom instead of SqlAzure as a provider.
In web.config add this
<SqlAuthenticationProviders>
<providers>
<add name="Active Directory Interactive" type="Microsoft.Azure.Services.AppAuthentication.SqlAppAuthenticationProvider, Microsoft.Azure.Services.AppAuthentication" />
</providers>
</SqlAuthenticationProviders>
Make sure you have added the identity user in your Azure SQL and granted required privileges.
CREATE USER [MyAppIdentity] FROM EXTERNAL PROVIDER
GO
ALTER ROLE db_datareader ADD MEMBER [MyAppIdentity];
ALTER ROLE db_datawriter ADD MEMBER [MyAppIdentity];
Once you deploy the application, please put your application settings and connection string to your webapp Application Settings option on Azure. Refer to this article.
Note: It has pulled the value from the App Settings configured in the Azure App Service’s – Application Settings blade but not from the Web.config file. This way, you can change these configurable values whenever you like to change without depending on developers. The same rule applies even for Connection String.
Unable to get the access token by directly passing the username and password
Endpoint : https://login.microsoftonline.com/{tenant_id}/oauth2/token
grant_type: password
client_id: APPLICATION_ID
resource: https://graph.microsoft.com/.default
username: <username#microsoft.com>
password: <password>
Scope : openid
App is created in https://apps.dev.microsoft.com/
Getting Invalid grant error:
{
"error": "invalid_grant",
"error_description": "AADSTS70002: Error validating credentials. AADSTS50126: Invalid username or password\r\nTrace ID: 1ff96bc3-29c8-48f1-b7cc-f77c01525500\r\nCorrelation ID: 9821fdf5-25dc-4b07-84b3-f084194ea123\r\nTimestamp: 2018-09-14 20:04:01Z",
"error_codes": [
70002,
50126
],
"timestamp": "2018-09-14 20:04:01Z",
"trace_id": "1ff96bc3-29c8-48f1-b7cc-f77c01525500",
"correlation_id": "9821fdf5-25dc-4b07-84b3-f084194ea123"
}
UPDATE
Looks like there are more than one issues in play here.
You were using Azure AD token endpoint but had registered your application with Azure AD B2C by mistake (so case 2 as per my original answer).
Now after correcting that one, you should be using clientid and client secret for this new application that is registered with Azure AD.
Make sure you have added Microsoft Graph permissions for your application in Azure AD under "required permissions" and at the end of selecting appropriate permissions, make sure you press on the "Grant Permissions" button to give consent.
Looking at the error message and code you are getting (invalid_grant and "AADSTS70002: Error validating credentials. AADSTS50126"), I tried out ROPC exactly like you from Postman with a test application of my own and I tried multiple different combinations of passing wrong inputs, but the exact error codes you see come only in scenario where either my password or the username is incorrect (as the message says :)). In all other cases, error code will be different.
So, for username - make sure you give fully qualified name e.g. rohitsaigal#mydomain.onmicrosoft.com
for password - pretty obvious.
Give it another try based on instructions above and lets see how it goes.
ORIGINAL ANSWER
App is created in https://apps.dev.microsoft.com/
This means that your application is registered with Azure AD B2C.
Where you have registered your application isn't matching with the token endpoint you are using.
Case 1 - You are looking to use Azure AD B2C
Resource Owner Password Credentials Grant is still in public preview and you will need to follow the instructions provided by Microsoft here -
Configure the resource owner password credentials flow in Azure AD B2C
The endpoint you will hit to get the token will also be different that the one you have mentioned.
https://yourtenant.b2clogin.com/<yourtenant.onmicrosoft.com>/oauth2/v2.0/token?p=B2C_1_ROPC_Auth
Case 2 - You are looking to use Azure AD B2B
In this case you are using the correct end point to get the token, but you have wrongly registered your application with Azure AD B2C, you will need to change that and register your application from Azure Portal.
Instructions and details here - Integrating applications with Azure Active Directory
Just in case you need to read up on differences between Azure AD B2B v/s B2C - look at this SO Post
Here is another useful SO Post that gives information about registering your application through Azure Portal v/s https://apps.dev.microsoft.com (New application registration portal)
It seems like you didn't Grant Permissions to your app. Make sure all of the users are added to the app and ensure that you have the correct web.config parameters.
Also, ensure that the username and password are correct for the managed domain to connect. I've gotten this error before using the incorrect user. A regular azure global admin user may not be able to authenticate. You need to make sure you are using a CSP admin user.
This works https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-ropc-policy?tabs=app-reg-ga&pivots=b2c-user-flow
But keep in mind that there are limitations like:
You cannot use when a password is expired or needs to be changed.
MFA is not supported
Social logins are not supported
I created a login named logintest (SQL Authentication) then i created a user named usertest with this login
the user creation is successful, And i changed the authentication mode to mixed mode and also restarted the services SQLSERVERAGENT and MSSQLSERVER
and still this error appear when i try to login with the new user created
Cannot connect to SARAH.
Login failed for user 'usertest'. (Microsoft SQL Server, Error: 18456)
The login must have CONNECT right given.
The login must be enabled.
The default database linked to the login must be a database to which the login has rights to connect (for example by default master database gives rights to guest user to connect).
USE [master]
GO
ALTER LOGIN [logintest] WITH DEFAULT_DATABASE=[master]
GO
GRANT CONNECT SQL TO [logintest]
GO
ALTER LOGIN [logintest] ENABLE
GO
Then make sure the password is correct and that guest user is enabled on master database.
I am using SSRS 2008 R2 to build a report that uses a Sharepoint list as its data source, to which it is configured to connect using Windows Authentication (Integrated Security). The problem is that when the report is deployed to the Report Server, the SharePoint source rejects the credentials, returning:
An error has occurred during report processing. (rsProcessingAborted)
Query execution failed for dataset 'ListDataset'. (rsErrorExecutingCommand)
An error occurred when accessing the specified SharePoint list. The connection string
might not be valid. Verify that the connection string is correct. (rsSPDataProviderError)
The request failed with HTTP status 401: Unauthorized.
The Sharepoint data source accepts my credentials when I test the report locally in BIDS, but does not accept them after they 'double-hop' from the Report Server. What is the best work-around? Do I need to create a Service Account in SSRS, supply those credentials in the data source within SSRS, and grant the necessary read permissions to the Service Account via Sharepoint? Any suggestions would be greatly appreciated.
This is the same answer to a similar question:
I usually create a user called Reportuser (e.g. reportuser#[domain].com). Create this user on your domain, make sure it has access to SharePoint.
In BIDS/visual studio in the properties for the datasource for your report, under the credentials tab, click the radio button next to "Use Windows Authentication (integrated security)". Upload the datasource to the report manager website. ( You've done this part).
Navigate to the Report manager website, and the properties of the uploaded datasource.
Under the section starting with "Connect using":
Check the "Credentials stored securely in the report server" option
Enter the username and password like this (where domain is replaced with the domain of your network): reportuser#domain.com password
Important part: Tick the "Use as Windows credentials when connecting to the data source"
Test the connection and will work - I have just tested it.