How do I get a token needed for DFS Kerberos authentication? - kerberos

I'm trying to write a client for consuming DFS (Documentum Foundation Services) and trying to use Kerberos for single sign-on. Both Java and C# sample code (productivity layer) in the documentation gives the following line which gets the Kerberos binary token:
byte[] ticket = ...
I'm not sure how to actually get the binary token, and the "..." doesn't help me. Does anyone know how to get an actual ticket (Kerberos token) using either Java or C#?
Here are the examples given for both Java and C#:
Java: Invoking a service with Kerberos authentication
KerberosTokenHandler handler = new KerberosTokenHandler();
IObjectService service = ServiceFactory
.getInstance().getRemoteService(..., contextRoot, Arrays.asList((Handler) handler));
byte[] ticket = ...;
handler.setBinarySecurityToken(
new KerberosBinarySecurityToken(ticket, KerberosValueType.KERBEROSV5_AP_REQ));
service.create(...)
C#: Invoking a service with Kerberos authentication
KerberosTokenHandler handler = new KerberosTokenHandler();
List<IEndpointBehavior> handlers = new List<IEndpointBehavior>();
handlers.Add(handler);
IObjectService service = ServiceFactory
.Instance.GetRemoteService<IObjectService>(..., contextRoot, handlers);
byte[] ticket = ...;
handler.SetBinarySecurityToken(
new KerberosBinarySecurityToken(ticket, KerberosValueType.GSS_KERBEROSV5_AP_REQ));
service.create(...);

I just figured this out for .NET and would like to share for those who maybe interested. What's needed is WSE3 library. Make sure to configure your DFS service account for Kerberos delegation.
So what need to do is set your KerberosTokenHandler with the Kerberos token. The KerberosBinarySecurityToken comes from WSE3. The code would look something like this:
KerberosTokenHandler kerberosTokenHandler = new KerberosTokenHandler();
String servicePrincipalName = “DFS/example66”; // this is the service principal name for your DFS service account in Active Directory.
using (KerberosClientContext kerberosClientContext = new KerberosClientContext(servicePrincipalName, true, ImpersonationLevel.Delegation))
{
KerberosBinarySecurityToken token = new KerberosBinarySecurityToken(kerberosClientContext.InitializeContext(), KerberosValueType.KERBEROSV5_AP_REQ);
kerberosTokenHandlerandler.SetBinarySecurityToken(token);
}

Related

Writing log to gcloud Vertex AI Endpoint using gcloud client fails with google.api_core.exceptions.MethodNotImplemented: 501

Trying to use google logging client library for writing logs into gcloud, specifically, i'm interested in writing logs that will be attached to a managed resource, in this case, a Vertex AI endpoint:
Code sample:
import logging
from google.api_core.client_options import ClientOptions
import google.cloud.logging_v2 as logging_v2
from google.oauth2 import service_account
def init_module_logger(module_name: str) -> logging.Logger:
module_logger = logging.getLogger(module_name)
module_logger.setLevel(settings.LOG_LEVEL)
credentials= service_account.Credentials.from_service_account_info(json.loads(SA_KEY_JSON))
client = logging_v2.client.Client(
credentials=credentials,
client_options=ClientOptions(api_endpoint="us-east1-aiplatform.googleapis.com"),
)
handler = client.get_default_handler(
resource=Resource(
type="aiplatform.googleapis.com/Endpoint",
labels={"endpoint_id": "ENDPOINT_NUMBER_ID",
"location": "us-east1"},
)
)
#Assume we have the formatter
handler.setFormatter(ENRICHED_FORMATTER)
module_logger.addHandler(handler)
return module_logger
logger = init_module_logger(__name__)
logger.info("This Fails with 501")
And i am getting:
google.api_core.exceptions.MethodNotImplemented: 501 The GRPC target
is not implemented on the server, host:
us-east1-aiplatform.googleapis.com, method:
/google.logging.v2.LoggingServiceV2/WriteLogEntries. Sent all pending
logs.
I thought we need to enable api and was told it's enabled, and that we have: https://www.googleapis.com/auth/logging.write
what could be causing the error?
As mentioned by #DazWilkin in the comment, the error is because the API endpoint us-east1-aiplatform.googleapis.com does not have a method called WriteLogEntries.
The above endpoint is used to send requests to Vertex AI services and not to Cloud Logging. The API endpoint to be used is the logging.googleapis.com as shown in the entries.write method. Refer to this documentation for more info.
The ClientOptions() function should have logging.googleapis.com as the api_endpoint parameter. If the client_options parameter is not specified, logging.googleapis.com is used by default.
After changing the api_endpoint parameter, I was able to successfully write the log entries. The ClientOptions() is as follows:
client = logging_v2.client.Client(
credentials=credentials,
client_options=ClientOptions(api_endpoint="logging.googleapis.com"),
)

Cannot access https://dev.azure.com/<myOrg> Using TFS extended client version 15

We are migrating some code that used to run against an on premise TFS server but now needs to run against Azure DevOps (previously Team Services). The credentials I'm using have been validated to successfully authenticate to our DevOps organization instance, but running the following code after referencing the
Microsoft.TeamFoundationServer.ExtendedClient
NuGet package always results in TF30063: You are not authorized to access https://dev.azure.com/<myOrg> The code is posted below for authenticating via non-interactive authentication. Do I need to use a different authentication mechanism or different credentials type to get this working?
System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(_userName, DecryptedPassword, _domain);
try
{
// Create TeamFoundationServer object
_teamFoundationCollection = new TfsTeamProjectCollection(_serverUrl, networkCredential);
_teamFoundationCollection.Authenticate();
}
catch (Exception ex)
{
// Not authorized
throw new TeamFoundationServerException(ex.Message, ex.InnerException)
}
Since you want to use .Net Client Libraries, you could refer to the following link:
https://learn.microsoft.com/en-us/azure/devops/integrate/concepts/dotnet-client-libraries?view=azure-devops
Patterns for use:
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
const String c_collectionUri = "https://dev.azure.com/fabrikam";
const String c_projectName = "MyGreatProject";
const String c_repoName = "MyRepo";
// Interactively ask the user for credentials, caching them so the user isn't constantly prompted
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
// Connect to Azure DevOps Services
VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);
// Get a GitHttpClient to talk to the Git endpoints
GitHttpClient gitClient = connection.GetClient<GitHttpClient>();
// Get data about a specific repository
var repo = gitClient.GetRepositoryAsync(c_projectName, c_repoName).Result;

ning.http.client Kerberos Example

How can I support Kerberos based authentication with the ning http client?
I am extending existing code which has support for NTLMAuth and I want to be able to include support for Kerberos, which is used on some of the websites that I need to test.
I want to be able to put in the user and password programmatically, I do not want to use a keyTab, or setup krb5 configuration on the system where this is running.
I have the following code block;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.Realm.RealmBuilder;
....
RealmBuilder myRealmBuilder = new RealmBuilder()
.setScheme(AuthScheme.KERBEROS)
.setUsePreemptiveAuth(true)
.setNtlmDomain(getDomain())
.setNtlmHost(getHost())
.setPrincipal(getUsername())
.setPassword(getUserPassword()));
RequestBuilder rb = new RequestBuilder()
.setMethod(site.getMethod())
.setUrl(site.getUrl())
.setFollowRedirects(site.isFollowRedirects())
.setRealm(myRealmBuilder),
site)
´´´
Currently I get the error response:
FAILED: Invalid name provided (Mechanism level: KrbException: Cannot locate default realm)
Does anyone have an good example of how to do this correctly?

How to fix Keberos Authentication prompt while running Java application

I wrote a Java application to connect with hive-metastore. It works fine but when I run the jar file on Linux it asks for Kerberos Username and password
. I already specified the Kerberos principal and keytab file in my code. And I don't want to use additional jass.config file. Is there any way to resolve that problem?
Here is my source code
HiveConf conf = new HiveConf();
MetastoreConf.setVar(conf, ConfVars.THRIFT_URIS, "thrift://HOSTNAME:9083");
MetastoreConf.setBoolVar(conf, ConfVars.USE_THRIFT_SASL, true);
MetastoreConf.setVar(conf, ConfVars.KERBEROS_PRINCIPAL, "hive/HOSTNAME#example.com");
MetastoreConf.setVar(conf, ConfVars.KERBEROS_KEYTAB_FILE, "hive.keytab");
System.setProperty("java.security.krb5.realm", "EXAMPLE.COM");
System.setProperty("java.security.krb5.kdc", "HOSTNAME");
System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
HiveMetaStoreClient client = new HiveMetaStoreClient(conf);
client.close();
Expected Result-
It should verify the connection successfully
Actual result-
java -jar Application
Kerberos username [root]:
Kerberos password [root]:
I want to bypass this kerberos terminal prompt authentication. Is there any way to do that?
final String user = "hive/HOSTNAME#EXAMPLE.COM";
final String keyPath = "hive.keytab";
Configuration conf = new Configuration();
System.out.println("In case of kerberos authentication");
conf.set("hadoop.security.authentication", "kerberos");
System.setProperty("java.security.krb5.kdc", "HOSTNAME");
System.setProperty("java.security.krb5.realm", "EXAMPLE.COM");
UserGroupInformation.setConfiguration(conf);
UserGroupInformation.loginUserFromKeytab(user, keyPath);
HiveConf conf1 = new HiveConf(); MetastoreConf.setVar(conf1,
ConfVars.THRIFT_URIS, "thrift://HOSTNAME:9083"); HiveMetaStoreClient
client = new HiveMetaStoreClient(conf1);
client.close();
It works fine now

python social auth load strategy and authenticate user manually with release 0.1.26

I used python social auth for social authentication in the last 2 months and it was great.
I needed QQ support, hence installed newest git commit (23e4e289ec426732324af106c7c2e24efea34aeb - not part of a release).
until now i used to authenticate the user using the following code:
# setup redirect uri in order to load strategy
uri = redirect_uri = "social:complete"
if uri and not uri.startswith('/'):
uri = reverse(redirect_uri, args=(backend,))
# load the strategy
try:
strategy = load_strategy(
request=request, backend=backend,
redirect_uri=uri, **kwargs
)
strategy = load_strategy(request=bundle.request)
except MissingBackend:
raise ImmediateHttpResponse(HttpNotFound('Backend not found'))
# get the backend for the strategy
backend = strategy.backend
# check backend type and set token accordingly
if isinstance(backend, BaseOAuth1):
token = {
'oauth_token': bundle.data.get('access_token'),
'oauth_token_secret': bundle.data.get('access_token_secret'),
}
elif isinstance(backend, BaseOAuth2):
token = bundle.data.get('access_token')
else:
raise ImmediateHttpResponse(HttpBadRequest('Wrong backend type'))
# authenticate the user
user = strategy.backend.do_auth(token)
which worked fine.
In the latest release this behaviour has changed, and an exception is raised since the "load_strategy" method has changed.
I can't seem to find any documentation on how to do it with the new release.
Any help would be appreciated!
Omri.
The last changes in the repository changed the importance of the strategy, instead of being the main entity to perform the authentication, it's just a helper class to glue the framework with the backends. Try with this snippet to load the strategy and the backend:
from social.apps.django_app.utils import load_strategy, load_backend
strategy = load_strategy(request)
backend = load_backend(strategy, backend, uri)
...
user = backend.do_auth(token)