Jasypt plugin with encryption / decryption in grails - grails

By the reference of the question Is it possible to use the Grails Jasypt plugin outside the GORM layer for simple String encryption and decryption?
i tried to implement it for my password encryption / decryption .
But every-time its giving different encrypted value for the same password . so how can i use the following code and the jasypt configuration ?
def authenticate(){
def jasyptConfig = grailsApplication.config.jasypt
org.jasypt.encryption.pbe.StandardPBEStringEncryptor stringEncryptor =
new org.jasypt.encryption.pbe.StandardPBEStringEncryptor(jasyptConfig)
def encrypted = stringEncryptor.encrypt(params.password)
}
jasypt {
algorithm = "PBEWITHSHA256AND256BITAES-CBC-BC"
providerName = "BC"
password = "test"
keyObtentionIterations = 1000
}

The salt!
If you don't care, just set a ZeroSaltGenerator instance to your Encryptor. By default, it is RandomSaltGenerator, so the outputs are different.

If you want to use ZeroSaltGenerator then you have to make following changes:
Inside your config.groovy:
jasypt {
encryptorRegisteredName = "gormEncryptor"
}
And in your resources.groovy:
beans = {
hibernateStringEncryptor(HibernatePBEStringEncryptor) {
registeredName = "gormEncryptor"
algorithm = "PBEWITHSHA256AND256BITAES-CBC-BC"
providerName = "BC"
password = "test"
keyObtentionIterations = 1
saltGenerator = new org.jasypt.salt.ZeroSaltGenerator()
}
}
And it will generate the same encrypted values everytime.

Related

Can't pass password from credentialsJSON to commitStatusPublisher (bitbucket server) Teamcity

It seems that i have an old version of commitStatusPublisher plugin and it can't convert credentialsJSON string to its value. In any other situation I can access password with
params.findRawParam("env.mypass")!!.value
or in buildstep, script content
$mypass
But commitStatusPublisher not working with it.
Code example
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.commitStatusPublisher
params {
password("env.mypass", "credentialsJSON:8420d5dc-1d32-4f9e-a74d-c9444be05c23", display = ParameterDisplay.HIDDEN)
}
features {
commitStatusPublisher {
publisher = bitbucketServer {
url = "https://bitbucket.domain.com/"
userName = "user"
password = params.findRawParam("env.mypass")!!.value
}
}
}
Maybe I can somehow extract 'raw' var to use it for that plugin?
for example
var pass = something("env.mypass")
features {
commitStatusPublisher {
publisher = bitbucketServer {
url = "https://bitbucket.domain.com/"
userName = "user"
password = pass
}
}
}
In the result i want to keep password in TC tokens and use it with my version of commitStatusPublisher
Seems like a bug.
Recreating the token resolves problem

No suitable driver found for jdbc:jtds:sqlserver in grails 2.4.3 + groovy 2.3 project

I am facing weird issue in my grail project and after trying a lot i am posting this question here.I have tried all the URL related combination form http://jtds.sourceforge.net/faq.html#noSuitableDriver and other stack over flow answers like Help me create a jTDS connection string.
I am working on grails 2.4.3 project with groovy 2.3 and trying to connect with SQL Server database using jtds 1.3.1 but always getting "No suitable driver found for jdbc:jtds:sqlserver:" But to test this scenario i have written stand alone program as given below for same data base using same jar jtds 1.3.1 and its working fine.
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = "jdbc:jtds:sqlserver://<hostname>:<port>/<database>";
Connection con = DriverManager.getConnection(url,"user","password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);}
Below I have provided the grails project code snippet for connection class
class SQLServerConnection implements DBConnection {
#Override
public Connection getConnection(String serverName, String databaseName) {
// TODO Auto-generated method stub
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = "jdbc:jtds:sqlserver://<host>:<port>/<database>";
Connection con = DriverManager.getConnection(url,"user","password");
return con
}
Action form where i am calling this method
def dataFaucetColumn (){
def currentApp = RawDataApp.get(params.int('id'))
String query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='"+currentApp?.tableName +"'"
Connection con = new SQLServerConnection().getConnection(currentApp?.servers,currentApp?.databaseName)
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query); }
waiting for your answers.
Here's how you can use SQL Server with Grails, while taking advantage of Hibernate:
Open grails-app/conf/BuildConfig.groovy
In the dependencies section add the JTDS dependency. Then save the file.
Example:
dependencies {
runtime 'net.sourceforge.jtds:jtds:1.3.1'
}
Open grails-app/conf/DataSource.groovy
In the environments section, set up the data source and save the file. In the following example I'll set up SQL Server for the production environment
Example:
environments {
production {
dataSource {
dbCreate = "update"
url = "jdbc:jtds:sqlserver://<hostname>:<port>/<database>"
username = "X"
password = "X"
driverClassName = "net.sourceforge.jtds.jdbc.Driver"
dialect = org.hibernate.dialect.SQLServerDialect
properties {
maxActive = 8
minEvictableIdleTimeMillis = 1800000
timeBetweenEvictionRunsMillis = 1800000
numTestsPerEvictionRun = 3
testOnBorrow = true
testWhileIdle = true
testOnReturn = true
validationQuery = "SELECT 1"
validationQueryTimeout = 3
validationInterval = 15000
jdbcInterceptors = "ConnectionState"
defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
}
}
}
}
That's it. Now you can use GORM to query the database. Plus, Hibernate will manage the database connection(s) :)

Defining an alternate connection pool in Grails 2.3.6

I know that, at some point between Grails 1.X and Grails 2.X, the default connection pooling library changed from commons-dbcp to tomcat-dbcp.
Now, I'm trying to configure either BoneCP or HikariCP as the connection pooling library for my Grails application.
However, I see that this answer offers a solution which might only apply to Grails 1.X.
I also found this Gist, but again, I don't know which Grails version it applies to.
So, is it possible to define a custom connection pool inside a Grails 2.3.6 application? Thanks!
UPDATE: OK so you actually need to tell Grails not to pool the datasources, since HikariCP is now taking care of this.
I saw connection weirdness in my apps if I left that switch on. So instead say:
pooled = false
OK yeah, #Joshua Moore is right.
I tried doing it with updated Grails methods and this is the relevant section of my resources.groovy file. As far as I can understand, the configuration values in Datasource.groovy are pulled into resources.groovy at runtime, after the target runtime environment has been identified (development, test or production).
def config = Holders.config
def dataSources = config.findAll {
it.key.toString().contains("dataSource_")
}
dataSources.each { key, value ->
def ds = value
"${key}"(HikariDataSource, { bean ->
def hp = new Properties()
hp.username = ds.username
hp.password = ds.password
hp.connectionTimeout = 6000
hp.maximumPoolSize = 60
hp.jdbcUrl = ds.url
hp.driverClassName = ds.driverClassName
HikariConfig hc = new HikariConfig(hp)
bean.constructorArgs = [hc]
})
}
And this is the relevant section of my DataSource.groovy configuration:
// environment specific settings
environments {
development {
dataSource_myapp1 {
pooled = false
username = "CONFIGURE_ME_EXTERNALLY"
password = "CONFIGURE_ME_EXTERNALLY"
driverClassName = 'oracle.jdbc.OracleDriver'
dialect = 'org.hibernate.dialect.Oracle10gDialect'
url = 'jdbc:oracle:thin:#MYDBHOST1:1521/MYSERVICEID1'
}
dataSource_myApp2 {
pooled = false
username = "CONFIGURE_ME_EXTERNALLY"
password = "CONFIGURE_ME_EXTERNALLY"
driverClassName = 'oracle.jdbc.OracleDriver'
dialect = 'org.hibernate.dialect.Oracle10gDialect'
url = 'jdbc:oracle:thin:#MYDBHOST2:1521/MYSERVICEID2'
}
}
}
In my case, it's pretty much the same for test and production environments. Thanks!

Multiple domains for oauth providers configuration in Grails 2.3

using Grails 2.3.8 and
plugins {
compile ':spring-security-core:2.0-RC2'
compile ':spring-security-oauth:2.0.2'
compile ':spring-security-oauth-facebook:0.1'
compile ':spring-security-oauth-google:0.1'
}
and the default providers setup:
oauth{
providers{
facebook{
api = org.scribe.builder.api.FacebookApi
key = '11111'
secret = '222222'
successUri = "http://localhost:8880/oauth/facebook/success"
failureUri = "http://localhost:8880/oauth/facebook/error"
callback = "http://localhost:8880/oauth/facebook/callback"
scope = 'email'
}
}
As I understood, I have to use the absolute URL's for callbacks. That is a problem, as my app is mapped to several domains, like myapp.com, myapp.de, myapp.ru etc.
Is it possible out of the box to provide the callback URL's for each domain?
TIA
so, I figured it out!
the solution contains a bit of ugliness, but works like charm:
in my Config I had to change the providers so, that the server name is reflected in provider name and callback-URLs:
oauth{
providers{
facebook{
api = org.scribe.builder.api.FacebookApi
key = '11111'
secret = '22222222'
scope = 'email'
}
'facebook_localhost'{
api = org.scribe.builder.api.FacebookApi
key = '111111'
secret = '222222222'
successUri = "http://localhost:8880/oauth/facebook_localhost/success"
failureUri = "http://localhost:8880/oauth/facebook_localhost/error"
callback = "http://localhost:8880/oauth/facebook_localhost/callback"
scope = 'email'
}
'facebook_wwwmysitenet'{
api = org.scribe.builder.api.FacebookApi
key = '9999999'
secret = '888888888888'
successUri = "http://www.mesite.net/oauth/facebook_wwwmesitenet/success"
failureUri = "http://www.mesite.net/oauth/facebook_wwwmesitenet/error"
callback = "http://www.mesite.net/oauth/facebook_wwwmesitenet/callback"
scope = 'email'
}
}
}
to make processing easier, I remove the dots from the server name.
The same I made for google.

Grails2.1 Dynamic mail configuration

I am trying to send an email from a grails app. I tried with recommended settings using gmail and it worked fine. I sent mail successfully. But I want to override the username and password dynamically. I don't know how can I do it. Can anybody help?
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "faruq#gmail.com" // Want to change dynamically like variable ${branch.mail}
password = "12345" // Want to change dynamically like variable ${branch.pass}
props = [
"mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"
]
}
}
I use this process for overriding the username from the controller
grailsApplication.config.grails.mail.username = Branch.get(2).mail
by this process username successfully changes
here Branch is my domain class and mail is property
but an authentication problem comes up:
javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted
Now what can I do?
You can use an external configuration file - put placeholder values in the main Config.groovy
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "<changeme>"
password = "<changeme>"
props = [
"mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"
]
}
}
and then override them with the correct values in the external config:
grails {
mail {
username = "faruq#gmail.com"
password = "12345"
}
}
To be able to change the credentials dynamically at run time it gets rather more complicated. Under the covers the mail plugin creates a Spring bean which is an instance of JavaMailSenderImpl to handle the actual sending of emails, and this bean is configured by default with static settings from the config. But at runtime this class appears to call its own getUsername() and getPassword() every time it needs to send a message. So you could replace this bean with your own custom subclass of JavaMailSenderImpl that overrides these methods to pull the details from the request context (code example, not tested, and imports/error handling omitted):
src/groovy/com/example/RequestCredentialsMailSender.groovy
class RequestCredentialsMailSender extends JavaMailSenderImpl {
public String getUsername() {
return RequestContextHolder.requestAttributes?.currentRequest?.mailUsername ?: super.getUsername()
}
public String getPassword() {
return RequestContextHolder.requestAttributes?.currentRequest?.mailPassword ?: super.getPassword()
}
}
You'd have to register this bean in your resources.groovy, and duplicate a fair bit of the configuration from the mail plugin itself, which is less than ideal:
grails-app/conf/spring/resources.groovy
beans = {
mailSender(com.example.RequestCredentialsMailSender) {
def mailConf = application.config.grails.mail
host = mailConf.host
port = mailConf.port
username = mailConf.username // the default, if not set in request
password = mailConf.password
protocol = mailConf.protocol
javaMailProperties = mailConf.props
}
}
Now when you need to send mail from a controller you can do
request.mailUsername = Branch.get(2).mail
request.mailPassword = Branch.get(2).mailPassword
sendMail { ... }
Just wanted to verify Ian's answer and expand it.
In the default Config.groovy file I have the added external config line:
grails.config.locations = [
"file:./${appName}-config.groovy",
"classpath:${appName}-config.groovy"
]
....
// and here is the mail config as above
grails{
mail{
....
In the config file at the root level I have my config file: TestApp-config.groovy (where TestApp is the name of my app) as above:
grails {
mail {
username = "faruq#gmail.com"
password = "12345"
}
}
Didn't need anything past this and it worked great.
We can also use replyTo field if our aim is only to get the reply back on specific Email Id. We can dynamically pass an email id to "replyTo" field and can expect an email back on the same.
Example :
asynchronousMailService.sendMail
{
to ["xyz#gmail.com","pqr#gmail.com"]
subject "Subject Text"
if(ccs) cc ["xyz1#gmail.com","pqr1#gmail.com"]
if(bccs) bcc ["xyz2#gmail.com","pqr2#gmail.com"]
if(replyTo) replyTo "xyz#gmail.com"
if(attachBytes) attachBytes attachBytes
}
NOTE: Adding "replyTo" will only allow us to get the emails back on the specified email-id and will not send the email from the configured email.
It was suitable in my use case. Hope it helps !

Resources