Authentication using a login and password
Static authentication (login and password) passes a user/password pair when connecting to YDB. This method is used on dedicated installations YDB where login and password authentication is enabled. Typical steps: set the login and password, create a static credentials provider, open a transport, and execute a query. Details are in the Authentication section; basic connection is in the driver initialization recipe. Other methods: token, anonymous, environment variables, metadata, service account.
Below are authentication code examples using a login and password in different YDB SDKs.
#include <ydb-cpp-sdk/client/driver/driver.h>
#include <ydb-cpp-sdk/client/types/credentials/credentials.h>
NYdb::TDriver CreateDriverWithStaticCredentials(
const std::string& connectionString,
const std::string& user,
const std::string& password)
{
auto config = NYdb::TDriverConfig(connectionString)
.SetCredentialsProviderFactory(NYdb::CreateLoginCredentialsProviderFactory({
.User = user,
.Password = password,
}));
return NYdb::TDriver(config);
}
secdist
{
"ydb_settings": {
"db": {
"user": "user",
"password": "password"
}
}
}
Initialization code ydb::YdbComponent, obtaining ydb::TableClient and starting components::MinimalServerComponentList — as in the example from init.md.
You can pass the login and password as part of the connection string. For example:
"grpcs://login:password@localhost:2135/local"
You can also pass the login and password explicitly via the ydb.WithStaticCredentials option:
package main
import (
"context"
"os"
"github.com/ydb-platform/ydb-go-sdk/v3"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
db, err := ydb.Open(ctx,
os.Getenv("YDB_CONNECTION_STRING"),
ydb.WithStaticCredentials("user", "password"),
)
if err != nil {
panic(err)
}
defer db.Close(ctx)
...
}
You can pass the login and password as part of the connection string. For example:
package main
import (
"context"
_ "github.com/ydb-platform/ydb-go-sdk/v3"
)
func main() {
db, err := sql.Open("ydb", "grpcs://login:password@localohost:2135/local")
if err != nil {
panic(err)
}
defer db.Close()
...
}
You can also pass the login and password explicitly when initializing the driver through a connector using the special ydb.WithStaticCredentials option:
package main
import (
"context"
"os"
"github.com/ydb-platform/ydb-go-sdk/v3"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
nativeDriver, err := ydb.Open(ctx,
os.Getenv("YDB_CONNECTION_STRING"),
ydb.WithStaticCredentials("user", "password"),
)
if err != nil {
panic(err)
}
defer nativeDriver.Close(ctx)
connector, err := ydb.Connector(nativeDriver)
if err != nil {
panic(err)
}
db := sql.OpenDB(connector)
defer db.Close()
...
}
import tech.ydb.common.transaction.TxMode;
import tech.ydb.auth.StaticCredentials;
import tech.ydb.core.grpc.GrpcTransport;
import tech.ydb.query.QueryClient;
import tech.ydb.query.result.ResultSetReader;
import tech.ydb.query.tools.QueryReader;
import tech.ydb.query.tools.SessionRetryContext;
public class StaticAuthExample {
public static void main(String[] args) throws Exception {
// Connection string from environment variable or local YDB by default
String connectionString = System.getenv().getOrDefault(
"YDB_CONNECTION_STRING", "grpc://localhost:2136/local");
String username = System.getenv("YDB_USER");
String password = System.getenv("YDB_PASSWORD");
if (username == null || username.isEmpty() || password == null) {
throw new IllegalStateException("Задайте переменные окружения YDB_USER и YDB_PASSWORD");
}
try (GrpcTransport transport = GrpcTransport.forConnectionString(connectionString)
.withAuthProvider(new StaticCredentials(username, password))
.build();
QueryClient queryClient = QueryClient.newClient(transport).build()) {
SessionRetryContext retryCtx = SessionRetryContext.create(queryClient).build();
QueryReader reader = retryCtx.supplyResult(
session -> QueryReader.readFrom(session.createQuery("SELECT 1", TxMode.NONE))
).join().getValue();
// Connection check: output the result SELECT 1
ResultSetReader rs = reader.getResultSet(0);
if (rs.next()) {
System.out.println("SELECT 1 = " + rs.getColumn(0).getInt32());
}
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Properties;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class StaticAuthJdbcExample {
public static void main(String[] args) throws SQLException {
String jdbcUrl = System.getenv().getOrDefault(
"YDB_JDBC_URL", "jdbc:ydb:grpc://localhost:2136/local");
String username = System.getenv("YDB_USER");
String password = System.getenv("YDB_PASSWORD");
if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
throw new IllegalStateException("Задайте переменные окружения YDB_USER и YDB_PASSWORD");
}
Properties props = new Properties();
props.setProperty("username", username);
props.setProperty("password", password);
try (Connection connection = DriverManager.getConnection(jdbcUrl, props);
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT 1")) {
if (rs.next()) {
System.out.println("SELECT 1 = " + rs.getInt(1));
}
}
}
}
You can also pass the login and password as the second and third arguments of the DriverManager.getConnection(jdbcUrl, username, password) method.
In Spring Boot, ORM, and other third-party frameworks around JDBC, set the same JDBC URL, login, and password as in the example above (for example, spring.datasource.url, spring.datasource.username, spring.datasource.password or an equivalent in the pool configuration).
import { Driver } from "@ydbjs/core";
import { StaticCredentialsProvider } from "@ydbjs/auth/static";
const driver = new Driver("grpc://localhost:2136/local", {
credentialsProvider: new StaticCredentialsProvider(
{ username: user, password: password },
"grpc://localhost:2136",
),
});
await driver.ready();
import os
import ydb
config = ydb.DriverConfig(
endpoint=os.environ["YDB_ENDPOINT"],
database=os.environ["YDB_DATABASE"],
)
credentials = ydb.StaticCredentials(
driver_config=config,
user=os.environ["YDB_USER"],
password=os.environ["YDB_PASSWORD"]
)
with ydb.Driver(driver_config=config, credentials=credentials) as driver:
driver.wait(timeout=5)
...
import os
import ydb
import asyncio
config = ydb.DriverConfig(
endpoint=os.environ["YDB_ENDPOINT"],
database=os.environ["YDB_DATABASE"],
)
credentials = ydb.StaticCredentials(
driver_config=config,
user=os.environ["YDB_USER"],
password=os.environ["YDB_PASSWORD"],
)
async def ydb_init():
async with ydb.aio.Driver(driver_config=config, credentials=credentials) as driver:
await driver.wait()
...
asyncio.run(ydb_init())
import os
import sqlalchemy as sa
engine = sa.create_engine(
"yql+ydb://localhost:2136/local",
connect_args={
"credentials": {
"username": os.environ["YDB_USER"],
"password": os.environ["YDB_PASSWORD"]
}
}
)
with engine.connect() as connection:
result = connection.execute(sa.text("SELECT 1"))
using Ydb.Sdk.Ado;
await using var dataSource = new YdbDataSource(
"Host=localhost;Port=2136;Database=/local;User=user;Password=password");
await using var connection = await dataSource.OpenConnectionAsync();
use ydb::{ClientBuilder, StaticCredentials, YdbResult};
let client = ClientBuilder::new_from_connection_string("grpc://localhost:2136?database=local")?
.with_credentials(StaticCredentials::new(
std::env::var("YDB_USER")?,
std::env::var("YDB_PASSWORD")?,
http::Uri::from_static("grpc://localhost:2136"),
"local".into(),
))
.client()?;
<?php
use YdbPlatform\Ydb\Ydb;
use YdbPlatform\Ydb\Auth\Implement\StaticAuthentication;
$config = [
// Database path
'database' => '/local',
// Database endpoint
'endpoint' => 'localhost:2136',
// Auto discovery (dedicated server only)
'discovery' => false,
// IAM config
'iam_config' => [
'insecure' => true,
// 'root_cert_file' => './CA.pem', // Root CA file (uncomment for dedicated server)
],
'credentials' => new StaticAuthentication($user, $password)
];
$ydb = new Ydb($config);