MongoDB config for Spring Boot - 'url' with and without authentication credentials - mongodb

I want to make the application.yml work with and without username/password when running tests. My server needs the credentials but when I am on localhost I want it to work without an authentication and with the default settings. The spring profile ("integrationtest") should stay the same.
I have the following Spring Boot MongoDB config:
mongodb:
uri: mongodb://${mongodb_username:testuser}:${mongodb_password:testpassword}#${mongodb_ip:localhost}:${mongodb_port:27017}/testDB
If I remove the username and password I get this Error:
org.springframework.data.mongodb.UncategorizedMongoDbException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='testuser', source='testDB', password=<hidden>, mechanismProperties=<hidden>}; nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='testuser', source='testDB', password=<hidden>, mechanismProperties=<hidden>}
Caused by: com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed"}
How can I make it work with the same profile? Maybe there is a way with nested variables? Thank you.

A simple solution is to put the complete uri in a single variable, localhost works with the default config and the server specifies the uri at server start. The config looks like:
uri: ${mongodb_uri:mongodb://localhost:27017/testDB}
At server start override it with:
-Dmongodb_uri=mongodb://testUser:testPassword#example.com:27017/testDB

Related

Keycloak Admin Client throws error in server logs

am using keycloak admin client with my custom SPI.
I am getting this error when am trying to to create keycloak builder.
previously i tried this solution also but this didnt worked for me.
keycloak version 20.0.2 quarkus dist
this is the code I am using for builder
KeycloakBuilder.builder()
.serverUrl("http://localhost:8080/")
.realm("xxxxx")
.username("xxxx")
.password("xxxxx")
.clientId("admin-cli")
.resteasyClient(
new ResteasyClientBuilder()
.connectionPoolSize(10).build()
).build();
here's the error log
2023-01-26 13:11:33,684 ERROR [org.keycloak.services.error.KeycloakErrorHandler] (executor-thread-4) Uncaught server error: java.lang.InstantiationError: org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder
at com.nafath.keycloak.NafathTokenAuthenticator.getKeycloakInstance(NafathTokenAuthenticator.java:178)
at com.nafath.keycloak.NafathTokenAuthenticator.saveNewUser(NafathTokenAuthenticator.java:127)
at com.nafath.keycloak.NafathTokenAuthenticator.authenticate(NafathTokenAuthenticator.java:116)
at org.keycloak.authentication.DefaultAuthenticationFlow.processSingleFlowExecutionModel(DefaultAuthenticationFlow.java:446)
at org.keycloak.authentication.DefaultAuthenticationFlow.processFlow(DefaultAuthenticationFlow.java:250)
at org.keycloak.authentication.AuthenticationProcessor.authenticateOnly(AuthenticationProcessor.java:1017)
at org.keycloak.authentication.AuthenticationProcessor.authenticate(AuthenticationProcessor.java:879)
at org.keycloak.protocol.AuthorizationEndpointBase.handleBrowserAuthenticationRequest(AuthorizationEndpointBase.java:151)
at org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint.buildAuthorizationCodeAuthorizationResponse(AuthorizationEndpoint.java:338)
at org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint.process(AuthorizationEndpoint.java:194)
at org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint.buildGet(AuthorizationEndpoint.java:112)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:170)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:130)
at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:660)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:524)
at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$2(ResourceMethodInvoker.java:474)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:476)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:434)
at org.jboss.resteasy.core.ResourceLocatorInvoker.invokeOnTargetObject(ResourceLocatorInvoker.java:192)
at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:152)
at org.jboss.resteasy.core.ResourceLocatorInvoker.invokeOnTargetObject(ResourceLocatorInvoker.java:183)
at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:141)
at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:32)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:492)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:261)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:161)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:164)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:247)
at io.quarkus.resteasy.runtime.standalone.RequestDispatcher.service(RequestDispatcher.java:73)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatch(VertxRequestHandler.java:151)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.handle(VertxRequestHandler.java:82)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.handle(VertxRequestHandler.java:42)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1284)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:173)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:140)
at io.quarkus.vertx.http.runtime.StaticResourcesRecorder$2.handle(StaticResourcesRecorder.java:84)
at io.quarkus.vertx.http.runtime.StaticResourcesRecorder$2.handle(StaticResourcesRecorder.java:71)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1284)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:173)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:140)
at io.quarkus.vertx.http.runtime.VertxHttpRecorder$6.handle(VertxHttpRecorder.java:430)
at io.quarkus.vertx.http.runtime.VertxHttpRecorder$6.handle(VertxHttpRecorder.java:408)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1284)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:173)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:140)
at org.keycloak.quarkus.runtime.integration.web.QuarkusRequestFilter.lambda$createBlockingHandler$0(QuarkusRequestFilter.java:82)
at io.quarkus.vertx.core.runtime.VertxCoreRecorder$14.runWith(VertxCoreRecorder.java:564)
at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29)
at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:833)
I tried it with resteasy version 4

Dataproc trying to connect to Postgres through JDBC, missing permissions

Thanks in advance...
I want to connect/write using JDBC APIs to a Postgres SQL instance running using Cloud SQL programmatically. I have used following jars:
postgresql
postgres-socket-factory
postgres-socket-factory-1.0.11-jar-with-dependencies.jar
I am running Dataproc which will try to connect using step #1, but I get following exception:
2019-04-01 11:05:03.998 IST
Something unusual has occurred to cause the driver to fail. Please report this exception.
at org.postgresql.Driver.connect(Driver.java:277)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at rdsConnector$.getConnection(rdsConnector.scala:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.spark.deploy.yarn.ApplicationMaster$$anon$4.run(ApplicationMaster.scala:721)
Caused by: java.lang.RuntimeException: Unable to retrieve information about Cloud SQL instance [projectID:us-east1:dB]
at com.google.cloud.sql.core.SslSocketFactory.obtainInstanceMetadata(SslSocketFactory.java:459)
at com.google.cloud.sql.core.SslSocketFactory.fetchInstanceSslInfo(SslSocketFactory.java:333)
at com.google.cloud.sql.core.SslSocketFactory.getInstanceSslInfo(SslSocketFactory.java:313)
at com.google.cloud.sql.core.SslSocketFactory.createAndConfigureSocket(SslSocketFactory.java:194)
at com.google.cloud.sql.core.SslSocketFactory.create(SslSocketFactory.java:160)
at com.google.cloud.sql.postgres.SocketFactory.createSocket(SocketFactory.java:96)
at org.postgresql.core.PGStream.<init>(PGStream.java:62)
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:91)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:192)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
at org.postgresql.Driver.makeConnection(Driver.java:454)
at org.postgresql.Driver.connect(Driver.java:256)
... 11 more
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
2019-04-01 11:05:03.000 IST
User class threw exception: org.postgresql.util.PSQLException: Something unusual has occurred to cause the driver to fail. Please report this exception.
I understand this as a permission issue, but since I am using Dataproc to connect to Postgres what permission is missing? if I was running from a local laptop machine then I have to set GOOGLE_APPLICATION_CREDENTIALS to a json file. But what is the process in case of Dataproc?
The JDBC SocketFactory uses the Application Default Credentials strategy for accessing account credentials.
For Cloud Dataproc, a default service account is provided for you at [project-number]-compute#developer.gserviceaccount.com. You grant this account the "Cloud SQL Client" IAM role, the JDBC SocketFactory will use it to authenticate, and thus you will be able to connect to your application.
Just leave further notes for future visitors:
If the error you're getting is like:
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Insufficient Permission",
"reason" : "insufficientPermissions"
} ],
"message" : "Request had insufficient authentication scopes.",
"status" : "PERMISSION_DENIED"
}
then it could be caused by issues with the scopes (Cloud API access scopes) of the VM instances. One way to fix this is adding the scope of sql-admin when creating the Dataproc cluster. For example:
gcloud dataproc clusters create <your-cluster-name> \
--region=<your-region> \
--zone=<your-zone> \
--scopes=https://www.googleapis.com/auth/sqlservice.admin \
...
Another way is edited that in the VM instances.
See the gcloud documentation for details

Remote Invocation of EJB in WildFly 10 using JNDI lookup

Im trying to invoke an EJB from a remote server using JNDI lookup, Im using EJB3 with Spring-MVC in WildFly 10 and the configuration guided in this documentation has been done in my client and remote server
https://docs.jboss.org/author/display/WFLY10/EJB+invocations+from+a+remote+client+using+JNDI
But still I'm not able to get the connection of remote server.
1) Created a user under ApplicationRealm and gave the permissions for master slave setup for remote EJB Invocation.
2) This is my jboss-ejb-client.properties file, Here I have given the wildfly User_Name and Password of Host server.
endpoint.name=client-endpoint
remote.connections=one, two
remote.connection.one.host=172.16.25.26
remote.connection.one.port=8080
remote.connection.one.username=ABCD
remote.connection.one.password=ABCD#123
remote.connection.two.host=localhost
remote.connection.two.port=8080
remote.connection.two.username=guest
remote.connection.two.username=guest
# org.jboss.as.logging.per-deployment=true
My exception is
javax.naming.AuthenticationException: Failed to connect to any server. Servers tried:
[http-remoting://172.16.25.26:8080 (Authentication failed: all available authentication mechanisms failed:
JBOSS-LOCAL-USER: javax.security.sasl.SaslException: Failed to read server challenge [Caused by
java.io.FileNotFoundException: D:\wildfly-10.0.0.Final\standalone\tmp\auth\local3540175271681581878.challenge
(The system cannot find the file specified)]
DIGEST-MD5: javax.security.sasl.SaslException: DIGEST-MD5: Cannot perform callback to acquire realm,
authentication ID or password [Caused by javax.security.auth.callback.UnsupportedCallbackException])]
[Root exception is javax.security.sasl.SaslException: Authentication failed: all available authentication
mechanisms failed:
Please tell me what am I missing here thats causing this exception and what is the significance of secret-key generated while creating the user in wildfly and where to configure that key

MongoDB: PLAIN method not suported

I'm getting this message when I'm trying to deploy my war artifact. My app is using hibernate ogm and it's trying to build persistence context when it's deployed. The message I'm getting is:
org.hibernate.service.spi.ServiceException: OGM000071: Unable to start datatore provider Caused by: org.hibernate.service.spi.ServiceException: OGM000071: Unable to start datatore provider Caused by: org.hibernate.HibernateException: OGM001214: Unable to connect to MongoDB instance: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=mongo:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=PLAIN, userName='living', source='lvdb', password=, mechanismProperties={}}}, caused by {com.mongodb.MongoCommandException: Command failed with error 2: 'Unsupported mechanism PLAIN' on server mongo:27017. The full response is { \"supportedMechanisms\" : [\"MONGODB-CR\", \"MONGODB-X509\", \"SCRAM-SHA-1\"], \"ok\" : 0.0, \"errmsg\" : \"Unsupported mechanism PLAIN\", \"code\" : 2, \"codeName\" : \"BadValue\" }}}] Caused by: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=mongo:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=PLAIN, userName='living', source='lvdb', password=, mechanismProperties={}}}, caused by {com.mongodb.MongoCommandException: Command failed with error 2: 'Unsupported mechanism PLAIN' on server mongo:27017. The full response is { \"supportedMechanisms\" : [\"MONGODB-CR\", \"MONGODB-X509\", \"SCRAM-SHA-1\"], \"ok\" : 0.0, \"errmsg\" : \"Unsupported mechanism PLAIN\", \"code\" : 2, \"codeName\" : \"BadValue\" }}}]"}}
What do I need to do in order to use the other mechanisms?
You'd have to specificy the property hibernate.ogm.mongodb.authentication_mechanism (see here).
Which is the authentication mechanism you'd want to use? We may not support it yet, but if you let us know about your preference, we can try and look into making it work quickly.
For MongoDB, default supported mechanism is 'SCRAM-SHA-1'. So, while connecting, you need to specify this mechanism. I saw the same error when connecting to MongoDB through spring-data. While I didn't make any special configuration for mongo, first and obvious option for me to try was PLAIN mechanism for authentication. Finally, resolved it using SCRAM-SHA-1.
For Spring-data, code looked something like this:
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(mongoUser, mongoDB, mongoPass.toCharArray());
Hope this helps.

How to log connection info with Mybatis

When i have a error on a database connection, i need to log it (with Database name and username that tried to connect to the db, don't need to log the password), I use Sprig-Mybatis on my aplication.
Any ideas how to do that?
Best Regards
There is no other special way to do as a simple try/catch in java will get you the expection.
For example a simple program where I am calling a mybatis mapper method:
try{
List result = mapper.myBatisMapperMethod();//this is responsible to set up
//a connection and run a query
}
Suppose the above call fails due to invalid authentication say the below where my password is wrong connection
exception that I usually get in mybatis:
Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Login failed for user 'applicationUsername'.)
Caused by: org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Login failed for user 'applicationUsername'.)
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1225)
at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77)
... 65 more
Caused by:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'applicationUsername'.
what I do is have a simple catch to above try you can have an sql exception catched but here I use simply Exception.
catch(Exception e){
//Suppose you are using Log4j You can simply
logger.error("This is my error log message"+e.getMessage());
//The above will log any kind of exception including the authentication fail or you
can specifically log a particular kind of exception.Java wont log failed password it just logs the user who tried unless you explicitly want to log it.
}