How can I use ImageAnnotatorClient with explicit authentication? - google-api

It is clear how to use Storageclient with explicit authentication. It is also clear how to use ImageAnnotatorClient with implicit authentication. But how to use explicit authentication for ImageAnnotatorClient? It does not accept credenticals as input for the create method. I work with C#. I need the library for OCR purposes.

If by "explicit" you mean loading your credentials file in code, here is how I did it in Scala (vision v1.20.0):
val visionClient = {
val credStream = getInputStream( "my-api-key.json" )
val credentials = GoogleCredentials.fromStream(credStream)
val imageAnnotatorSettings = ImageAnnotatorSettings.newBuilder()
.setCredentialsProvider( FixedCredentialsProvider.create( credentials ) )
.build();
ImageAnnotatorClient.create( imageAnnotatorSettings )
}
You should be able to do something similar in C#.

Related

Hide password in Genexus beforeConnect procedure

I'm using the BeforeConnect option in Genexus. I put this code in a procedure...
&UserID = &websession.Get("db")
//select the Database depending on websession
Do Case
Case &UserID = "1"
&DataBase = "CambioDB1"
Case &UserID = "2"
&DataBase = "CambioDB2"
Otherwise
&DataBase = "CambioDB1" //default database
EndCase
//Change connection properties
&dbconn = GetDatastore("Default")
&dbconn.UserName = 'username'
&dbconn.UserPassword = 'password'
&dbconn.ConnectionData = "DATABASE=" + &DataBase.Trim() //SQLServer
... set the BeforeConnect property and it works.
But how can I avoid to put the password of the db in the code?
I was thinking to use a file to read from, but it would be an unencrypted password anyway.
How can I solve this? Is there a way to manage this or do I have to risk the password in clear text?
Nicola,
You may use the ConfigurationManager to read a value from the standard config file (client.cfg for Java, web.config for .net).
&MyPassword = ConfigurationManager.GetValue('MY_PASSWORD')
Add a value to your configuration file with the password.
For example:
MY_PASSWORD=my-db-password
You probably want to save the password encrypted for an extra layer of security.
Simple:
&EncPass = Encrypt64(&Password, &SysEncKey)
Stonger encryption:
https://wiki.genexus.com/commwiki/servlet/wiki?42682,Symmetric+Stream+Encryption
&EncPass = &SymmetricStreamCipher.DoEncrypt(symmetricStreamAlgorithm, key, iv, plainText)

Simulate session using WithServer

I am trying to port tests from using FakeRequest to using WithServer.
In order to simulate a session with FakeRequest, it is possible to use WithSession("key", "value") as suggested in this post: Testing controller with fake session
However when using WithServer, the test now looks like:
"render the users page" in WithServer {
val users = await(WS.url("http://localhost:" + port + "/users").get)
users.status must equalTo(OK)
users.body must contain("Users")
}
Since there is no WithSession(..) method available, I tried instead WithHeaders(..) (does that even make sense?), to no avail.
Any ideas?
Thanks
So I found this question, which is relatively old:
Add values to Session during testing (FakeRequest, FakeApplication)
The first answer to that question seems to have been a pull request to add .WithSession(...) to FakeRequest, but it was not applicable to WS.url
The second answer seems to give me what I need:
Create cookie:
val sessionCookie = Session.encodeAsCookie(Session(Map("key" -> "value")))
Create and execute request:
val users = await(WS.url("http://localhost:" + port + "/users")
.withHeaders(play.api.http.HeaderNames.COOKIE -> Cookies.encodeCookieHeader(Seq(sessionCookie))).get())
users.status must equalTo(OK)
users.body must contain("Users")
Finally, the assertions will pass properly, instead of redirecting me to the login page
Note: I am using Play 2.4, so I use Cookies.encodeCookieHeader, because Cookies.encode is deprecated

Java 8 kerberos constrained delegation

Is there any example on how to do constrained delegation with Java 8/7. I tried searching around with no luck
Best Regards
Here is the Java 8 code snippet that allows to generate a SPNEGO token with TGS ticket for an impersonated user:
GSSManager manager = GSSManager.getInstance();
GSSName userName = manager.createName("targetUser", GSSName.NT_USER_NAME);
GSSCredential impersonatedUserCreds =
((ExtendedGSSCredential)serviceCredentials).impersonate(userName);
final Oid KRB5_PRINCIPAL_OID = new Oid("1.2.840.113554.1.2.2.1");
GSSName servicePrincipal =
manager.createName("HTTP/webservice-host.domain.ltd", KRB5_PRINCIPAL_OID);
ExtendedGSSContext extendedContext =
(ExtendedGSSContext) manager.createContext(servicePrincipal,
new Oid("1.3.6.1.5.5.2"),
impersonatedUserCreds,
GSSContext.DEFAULT_LIFETIME);
final byte[] token = extendedContext.initSecContext(new byte[0], 0, 0);
Beware extendedContext is not established yet. Multiple rounds with server may be required.
A simple demonstration code is available at https://github.com/ymartin59/java-kerberos-sfudemo
You may also refer to the follow project code: https://github.com/tellisnz/collared-kerberos

How to validate url which is used to register resource using rest api?

How to validate url which is used to register resource using REST API?
For example:
REST API POST http://xyz.wt.com:7001/rd?endpoint=node1&domain=D&EXTRA=qsjoiusswq2
In this I need to validate that the URL contains info only about endpoint and domain, EXTRA is useless, and how to find is there any extra info end user is passing?
For most programming languages there are libraries to parse URLs.
For Python, you could use urllib.parse.urlparse and urllib.parse.parse_qs:
import urllib
url = "http://xyz.wt.com:7001/rd?endpoint=node1&domain=D&EXTRA=qsjoiusswq2"
result = urllib.parse.urlparse(url)
query = urllib.parse.parse_qs(result.query)
print(query)
keys = set(urllib.parse.parse_qs(result.query).keys())
print(keys):
print(keys == {"domain", "endpoint"}
Output:
{'endpoint': ['node1'], 'EXTRA': ['qsjoiusswq2'], 'domain': ['D']}
{'EXTRA', 'domain', 'endpoint'}
False
So you keys in the query are not what you expect.

Configuring grails spring security ldap plugin

here is a part of my perl cgi script (which is working..):
use Net::LDAP;
use Net::LDAP::Entry;
...
$edn = "DC=xyz,DC=com";
$quser ="(&(objectClass=user)(cn=$username))";
$ad = Net::LDAP->new("ip_address...");
$ldap_msg=$ad->bind("$username\#xyz.com", password=>$password);
my $result = $ad->search( base=>$edn,
scope=>"sub",
filter=>$quser);
my $entry;
my $myname;
my $emailad;
my #entries = $result->entries;
foreach $entry (#entries) {
$myname = $entry->get_value("givenName");
$emailad = $entry->get_value("mail");
}
So basically, there is no admin/manager account for AD, users credentials are used for binding. I need to implement the same thing in grails..
+Is there a way to configure the plugin to search several ADs, I know I can add more ldap IPs in context.server but for each server I need a different search base...
++ I dont wanna use my DB, just AD. User logins through ldap > I get his email, and use the email for another ldap query but that will probably be another topic :)
Anyway the code so far is:
grails.plugin.springsecurity.ldap.context.managerDn = ''
grails.plugin.springsecurity.ldap.context.managerPassword = ''
grails.plugin.springsecurity.ldap.context.server = 'ldap://address:389'
grails.plugin.springsecurity.ldap.authorities.ignorePartialResultException = true
grails.plugin.springsecurity.ldap.search.base = 'DC=xyz,DC=com'
grails.plugin.springsecurity.ldap.authenticator.useBind=true
grails.plugin.springsecurity.ldap.authorities.retrieveDatabaseRoles = false
grails.plugin.springsecurity.ldap.search.filter="sAMAccountName={0}"
grails.plugin.springsecurity.ldap.search.searchSubtree = true
grails.plugin.springsecurity.ldap.auth.hideUserNotFoundExceptions = false
grails.plugin.springsecurity.ldap.search.attributesToReturn =
['mail', 'givenName']
grails.plugin.springsecurity.providerNames=
['ldapAuthProvider',anonymousAuthenticationProvider']
grails.plugin.springsecurity.ldap.useRememberMe = false
grails.plugin.springsecurity.ldap.authorities.retrieveGroupRoles = false
grails.plugin.springsecurity.ldap.authorities.groupSearchBase ='DC=xyz,DC=com'
grails.plugin.springsecurity.ldap.authorities.groupSearchFilter = 'member={0}'
And the error code is: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C0906E8, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v1db1
And it's the same code for any user/pass I try :/
Heeeeelp! :)
The most important thing with grails and AD is to use ActiveDirectoryLdapAuthenticationProvider rather than LdapAuthenticationProvider as it will save a world of pain. To do this, just make the following changes:
In resources.groovy:
// Domain 1
ldapAuthProvider1(ActiveDirectoryLdapAuthenticationProvider,
"mydomain.com",
"ldap://mydomain.com/"
)
// Domain 2
ldapAuthProvider2(ActiveDirectoryLdapAuthenticationProvider,
"mydomain2.com",
"ldap://mydomain2.com/"
)
In Config.groovy:
grails.plugin.springsecurity.providerNames = ['ldapAuthProvider1', 'ldapAuthProvider2']
This is all the code you need. You can pretty much remove all other grails.plugin.springsecurity.ldap.* settings in Config.groovy as they don't apply to this AD setup.
Documentation:
http://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ldap-active-directory

Resources