Login failed for user token-identified principal when connecting via sql_driver_manager.getConnection - apache-spark-sql

I am trying to connect to Azure SQL using Service Principle to create views, but it says
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user ClientConnectionId: XXXXX-XXXX-XXXX
However, with the same SPN I was able to connect and create tables, read tables.
import adal
resource_app_id_url = "https://database.windows.net/"
service_principal_id = dbutils.secrets.get(scope = "XX", key = "XXX")
service_principal_secret = dbutils.secrets.get(scope = "XX", key = "spn-XXXX")
tenant_id = dbutils.secrets.get(scope = "XX", key = "xxId")
authority = "https://login.windows.net/" + tenant_id
azure_sql_url = "jdbc:sqlserver://xxxxxxx.windows.net"
database_name = "testDatabase"
encrypt = "true"
host_name_in_certificate = "*.database.windows.net"
context = adal.AuthenticationContext(authority)
token = context.acquire_token_with_client_credentials(resource_app_id_url, service_principal_id, service_principal_secret)
access_token = token["accessToken"]
using above code I am able to create and read tables. There is a requirement to create views so I am using sql_driver_manager to connect to Azure SQL
properties = spark._sc._gateway.jvm.java.util.Properties()
properties.setProperty("accessToken", access_token)
sql_driver_manager = spark._sc._gateway.jvm.java.sql.DriverManager
sql_con = sql_driver_manager.getConnection(azure_sql_url, properties)
query = """
create or alter view test_view as select * from dbo.test_table
"""
stmt = sql_con.createStatement()
stmt.executeUpdate(query)
stmt.close()
this is resulting in an error:
Py4JJavaError: An error occurred while calling
z:java.sql.DriverManager.getConnection. :
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user token-identified principal. ClientConnectionId:
If I try the same with username and password instead of token, it works but I just need to use spn token for authenticating.
Working code:
sql_driver_manager = spark._sc._gateway.jvm.java.sql.DriverManager
sql_con = sql_driver_manager.getConnection(azure_sql_url, username, password)
query = """
create or alter view test_view as select * from dbo.test_table
"""
stmt = sql_con.createStatement()
stmt.executeUpdate(query)
stmt.close()
What is that I am missing, can someone help me understand the issue. Thanks.

You can not use that method since it was built to execute an update statement and return indexes.
See documentation. Use the prepare() and execute() methods.
https://learn.microsoft.com/mt-mt/sql/connect/jdbc/reference/executeupdate-method-java-lang-string?view=azuresqldb-current
#
# 5 - Upsert from stage to active table.
# Grab driver manager conn, exec sp
#
driver_manager = spark._sc._gateway.jvm.java.sql.DriverManager
connection = driver_manager.getConnection(url, user_name, password)
connection.prepareCall("exec [stage].[UpsertFactInternetSales]").execute()
connection.close()
This is sample code from an article I wrote. It calls a stored procedure to execute an UPSERT. However, any DML or DDL will work as long as it does not return a result set.

Related

Why I'm getting an error in DataBricks connection with a SQL database?

I am trying to connect to a SQL Server but somehow i'm getting the below error when trying to connect to db from databricks using Python:
Error:java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbd.SQLServerDriver
My connection code is the next one:
jdbcHostname = "hostname"
jdbcDatabase = "databasename"
jdbcPort = port
username = 'username'
password = 'password'
jdbcUrl = "jdbc:sqlserver://{0}:{1};database={2}".format(jdbcHostname, jdbcPort, jdbcDatabase)
connectionProperties = {
"user" : username,
"password" : password,
"driver" : "com.microsoft.sqlserver.jdbd.SQLServerDriver"
}
The last code works, but when I try to execute a query I got the mentioned error coming out from the second code line from the next block:
pushdown_query = "select * from table"
df = spark.read.jdbc(url=jdbcUrl, table=pushdown_query, properties=connectionProperties)
display(df)
I tried to install different connectors but I have not been lucky with it, could you help me?

Not able to establish database connection -dberror(Connection.prepareStatement): 258 - insufficient privilege: Not authorized

I am new to SAP Hana cloud environment and was trying to learn sentiment analysis using Hana cloud platform. I am using the following code in my .xsjs script :
var body = "error";
var data = {
result : 0
};
var id = Number($.request.parameters.get("id"));
var word = $.request.parameters.get("word");
if(word.length!==0) {
try {
var conn = $.db.getConnection();
var query = 'call \"com.hana.cloud.platform.TwitterSenitmentAnalysis.DatabaseStore::update\"(?,?)';
var cst = conn.prepareCall(query);
cst.setString(1, word);
cst.setInteger(2, id);
var rs = cst.execute();
conn.commit();
rs = cst.getResultSet();
while(rs.next()) {
data.result = rs.getInteger(1);
}
body = JSON.stringify(data);
rs.close();
cst.close();
conn.close();
} catch (e) {
body = e.stack + e.message;
$.response.status = $.net.http.BAD_REQUEST;
conn.close();
}
}
I am able to use another xsjs service to connect to the database and perform select however when I try to perform update it gives me the following error :
Not able to establish database connection -dberror(Connection.prepareStatement): 258 - insufficient privilege: Not authorized
The schema name I am working with is called AMRIT and the user is called AMRIT as well. While trying to give object privileges to the AMRIT schema for the update I get the following error in the hana database cockpit:
8:07:22 PM (Security Editor) Changing 'AMRIT' user failed: 404 - Granting privilege 'UPDATE' on SCHEMA 'AMRIT' failed: insufficient privilege: Not authorized
please assist on how to solve this?
Should I be giving any additional privilege to the system user?
Thanks, regards
Please give insert privilege on your schema to user _SYS_REPO.

Connect to SQL Server through PDO : DATABASE on another server

On local PC this works.
$HmsDBuser = 'test';
$HmsDBpassword = 'password';
$HmsDBserver = 'Developer,1433';
$HmsDBdatabase = 'DBNAME';
$this->db = new PDO ("sqlsrv:Server=$HmsDBserver;Database=$HmsDBdatabase","$HmsDBuser","$HmsDBpassword", array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
My Slim Framework is on Server A: 121.55.0.25
My database is on another Server B: 121.55.0.21
$HmsDBuser = 'test';
$HmsDBpassword = 'password';
$HmsDBserver = '121.55.0.21\MYSERVER\MSSQLSERVER,1433';
$HmsDBdatabase = 'DBNAME';
$this->db = new PDO ("sqlsrv:Server=$HmsDBserver;Database=$HmsDBdatabase","$HmsDBuser","$HmsDBpassword", array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
and after I connect to the database, I call function with path "product" in Slim framework.
ERROR got on Console :
angular.js:8619 GET http://121.55.0.25/product-manager_servertest/api/v1/products 404 (Not Found)
Try it like this:
$HmsDBserver = '121.55.0.21\\MYSERVER\\MSSQLSERVER,1433';
Notes:
Escaped backslashes.
No space before port.
If it doesn't work, then use just the server name, like this:
$HmsDBserver = '<server-name>,1433';

create user with umbraco webservice

I'm trying the following code:
var myCarrier = new memberCarrier()
{
DisplayedName = "abemad123",
Email = "abemad123#gmail.com",
LoginName = "abemad123",
MembertypeId = 1062,
Id = 3,
Password = "abe"
};
var client = new UmbracoWebService.memberServiceSoapClient();
var tmp = client.create(myCarrier, 1062, "abemad123", "abemad123");
But I get this error:
Server was unable to process request. ---> No User exists with ID -1
What am I doing wrong?
Bug in Umbraco.
If user/pass to the webservice doesn't match it throws an exception "No User exists with ID -1"
Error should be: "Wrong password"

Apache Shiro login failed using JDBC Realm

I am trying to connect to oracle DB .
I want to retrieve list of passwords from data base using the authentication query. Here is my sample shiro.ini file:
# password matcher
passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher
passwordService = org.apache.shiro.authc.credential.DefaultPasswordService
passwordMatcher.passwordService = $passwordService
# datasource
ds = oracle.jdbc.pool.OracleDataSource
ds.URL = jdbc:oracle:thin:#matrix-oracle11g:1521:dev11g
ds.user = cit1am
ds.password = cit1
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = SELECT USR_PSWD FROM USR
jdbcRealm.credentialsMatcher = $passwordMatcher
jdbcRealm.dataSource = $ds
securityManager.realms = $jdbcRealm
[users]
[roles]
[urls]
Sample code snippet of login:
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
try{
// let's login the current user so we can check against roles and permissions:
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("cit1am", "cit1") ;
token.setRememberMe(true);
try {
currentUser.login(token); //problem occurs here
log.info("inside try block ==========>>" );
}
catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
}
I am getting following error:
[main] ERROR org.apache.shiro.realm.jdbc.JdbcRealm - There was a SQL error while authenticating user [cit1am]
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:271)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:445)
Please suggest what i am doing wrong?
After debugging more i found issue with my code and sql query in .ini file.
I changed following in .INI file
jdbcRealm.authenticationQuery = SELECT USR_PSWD FROM USR where USR_NM = ?
Also commented
#cm = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
#jdbcRealm.credentialsMatcher = $cm and removedconfiguration related to password matcher
I also removed role and permission check from java code.
As i have just started with shrio it's bit difficult to understand flow at start.
Though it can help some one in future.
Thanks