Unable to login DB using jasypt - spring

Hi I am using below maven dependency in my Spring boot application.
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.16</version>
</dependency>
I am using below command to encrypt my DB password.
encrypt input="test" password=test algorithm=PBEWithMD5AndDES
In my application.properties, i have below properties,
spring.datasource.url=jdbc:sqlserver://localhost:1234;database=TEST_DB
spring.datasource.username=test
spring.datasource.password=ENC(OPdJ9jOw7tbJR+MlptpCHg==)
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.poolName=SpringBootHikariCP
spring.datasource.maximumPoolSize=50
spring.datasource.minimumIdle=30
spring.datasource.maxLifetime=2000000
spring.datasource.connectionTimeout=30000
spring.datasource.idleTimeout=30000
spring.datasource.pool-prepared-statements=true
spring.datasource.max-open-prepared-statements=250
In my application code, i am able to get decrypted value of spring.datasource.password property. But when i use JDBCTemplate, i am getting below exception.
Edit :
Mistakenly added wrong stacktrace. Below is correct one. Due to 3 unsuccessful attempts, the password got expired.
[ERROR] 2018-09-03 04:50:45.578 [https-jsse-nio-8092-exec-9] util - LOG : Class :Controller|| Method :process || org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'test'. ClientConnectionId:ba0abe4d-014a-42d3-b39e-ec1efc0e7131
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:394)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:474)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:484)
at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:494)
at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:500)
at com.test.dao.AppDaoImpl.generateQuery(AppDaoImpl.java:77)
at com.test.dao.AppDaoImpl$$FastClassBySpringCGLIB$$5d4e5540.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
at com.test.dao.AppDaoImpl$$EnhancerBySpringCGLIB$$eb86c18b.generateQuery(<generated>)
It is not able to login to database. Below is my AppDaoImpl.java
#Repository
public class AppDaoImpl implements AppDao {
#Autowired
JdbcTemplate jdbcTemplate;
#Override
public Integer generateQuery(String id) throws ImpsException {
return jdbcTemplate.update(QueryConst.SQL_INSERT_QUERY, id);
}
}
Before jasypt, i was just autowiring my JDBCTemplate and everything was working fine. Now it is not able to login.
PS: I am running my application with
-Djasypt.encryptor.password=test -Djasypt.encryptor.algorithm=PBEWithMD5AndDES

From the message Reason: The password of the account has expired. its clear that password has expired.
Log in to SQL server as a system administrator. Change the password to something else. Make sure enforce password policy is off and then change the password back to the original password.
OR
Right click 'Username' and go to Properties
You can find 'Enforce password expiration' on login properties window, which needs to be unchecked.

Related

How to ensure Hikari connections are spawn with latest credentials?

I am using IAM credentials for my Spring DataSource to connect to Database. IAM credentials expire in 15 minutes. So the spring.datasource.hikari.maxLifeTime is set to 14 minutes.
However, the service runs properly for only 15 minutes. After that I see "org.postgresql.util.PSQLException: FATAL: PAM authentication failed for user ... error.
I suspect this issue is due to the Hikari connections running with outdated credentials.
However, I don't understand why the new Hikari connections, which are created after existing connection timeouts, are not loading the new IAM credentials.
Here is my Datasource:
#Configuration
public class DatabaseConfiguration {
#Value("${database.url:null}")
private String dataBaseURL;
#Value("${database.username:null}")
private String username;
#Bean
#Profile("postgres")
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.url(dataBaseURL);
dataSourceBuilder.username(username);
// extracting IAM credentials by calling IAM Token generator.
dataSourceBuilder.password(RdsIamHikariDataSource.getPassword(dataBaseURL, username));
return dataSourceBuilder.build();
}
}
Doing a google on the classname leads to this blog post. Assuming you are attempting to follow that (and haven't got it to work). Do the following.
Add the following to your application.properties.
spring.datasource.url=<your-url>
spring.datasource.username=<your-iam-role>
spring.datasource.type=package.of.your.RdsIamHikariDataSource
In your java config remove your DatabaseConfiguration, Spring Boot auto configuration will now take care of creating the proper datasource.

How to initialize Spring Boot security config with default username/password but not crash on second run?

Following the topical guide here and adding a BCrypt password encoder based on Baeldung's example here I have configured my Spring Boot application to use my database (set up separately, not auto-generated by an ORM or something) as its source of user details for authentication. This part of my security configuration (here) looks like this:
#Override
public void configure(AuthenticationManagerBuilder builder) throws Exception {
builder .jdbcAuthentication()
.dataSource(dataSource)
.withUser(User.withUsername("admin").password(passwordEncoder().encode("pass")).roles("SUPER"));
logger.debug("Configured app to use JDBC authentication with default database.");
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
On the first run, this works, creating a user called 'admin' with a hashed password and the specified role in the database. (This is a PostgreSQL database for what it's worth.) However, if I try to run the app again, it fails to start, crashing because it tried to create the same user again and got a duplicate primary key error.
What I'd like: I'd like Spring Boot to create the default user if it doesn't already exist, skip over it if one already exists.
Why: It is necessary to be able to log in to a newly initialized copy of the application, sometimes restarting several times, for testing and for experimentation on the developer's machine. My "production" database should already have an 'admin' login and the app should not overwrite it, or crash because it cannot.
My question, therefore, is: How can I initialize a default user in Spring Boot's jdbcAuthentication configuration in such a way that Spring Boot won't crash if the username already exists?
Alternatively: If I could INSERT a default user into the database with SQL when the database is spun up, I wouldn't need to do it in the Spring Boot configuration. But I don't know how to hash a password in an INSERT statement in a way that matches Spring Boot's hashing.
PS: I have another issue with my new configuration breaking some automated test classes (see the other question if interested).
You can use the alternative solution that you have thought using the option .withDefaultSchema() with the jdbcauthentication that you are using. As you have mentioned in that alternative that you may have to figure out way to use hashed password in that script.
Should you have any followup question, this baeldung blog post will help you.
https://www.baeldung.com/spring-security-jdbc-authentication
Hope this helps.

Spring Security returning 403 with correct username password

I'm trying to enable basic http authentication with a single static username password for the whole project. I have tried many things but none have been successful. This is the latest method that I am trying
My security configuration
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").hasAnyRole().and().httpBasic();
}
}
My application.properties
spring.security.user.name=myusername
spring.security.user.password=mypassword
When I go to one of my controllers I do get the username/password dialog. However if I enter the correct one I get a a page with the message
My Whitelabel Error Page
There was an unexpected error (type=Forbidden, status=403).
Forbidden
and in my spring logs I see
Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [150,084] milliseconds.
When I enter a wrong username password, the auth dialog keeps refreshing, so I am sure I am entering the correct username pass, and Spring is verifying that. But I don't understand why I get a 403 error when the page loads.

Spring Social: "Unable to get a ConnectionRepository: no user signed in"

I'm trying to use Facebook sign in as described in
https://github.com/spring-guides/gs-accessing-facebook
When I'm trying to create JdbcUsersConnectionRepository, I need spring security in class path.
And when I add spring security I receive
"java.lang.IllegalStateException: Unable to get a ConnectionRepository: no user signed in"
when trying to receive Connection
Connection<Facebook> connection = connectionRepository.findPrimaryConnection(Facebook.class);
or checking
if (!facebook.isAuthorized())
All this happens only when spring security is in the class path
Social Connection should be correspond to any auth user. It seems user should login through username/password or Service Provider. Try look at http://docs.spring.io/spring-social/docs/1.0.x/reference/html/signin.html
"java.lang.IllegalStateException: Unable to get a ConnectionRepository: no user signed in"
It happens because AuthenticationNameUserIdSource used by default
Internally, Spring Social’s configuration support will use the UsersConnectionRepository to create a request-scoped ConnectionRepository bean. In doing so, it must identify the current user. Therefore, we must also override the getUserIdSource() to return an instance of a UserIdSource.
In this case, we’re returning an instance of AuthenticationNameUserIdSource. This implementation of the UserIdSource interface assumes that the application is secured with Spring Security. It uses the SecurityContextHolder to lookup a SecurityContext, and from that return the name property of the Authentication object.
If your application isn’t secured with Spring Security, you’ll need to implement the UserIdSource interface as approprate for your application’s security mechanism. The UserIdSource interface looks like this:
package org.springframework.social;
public interface UserIdSource {
String getUserId();
}
The getUserId() method simply returns a String that uniquely identifies the current user.
More info here
If you are using Spring boot, then the property security basic should not be set to false. Hide this line in your application.properties. This disables the security and boot throws the error if spring-security is disabled.
#security.basic.enabled=false

Spring Security Core Grails Plugin Issue

I have just read the basic information for the spring security core grails plugin and installed it in my grail project :
grails install-plugin spring-security-core
After that I have used s2-quickstart providing by the plugin :
grails s2-quickstart com.springsecurity SpringUser SpringRole
So basically it has created required Login and Logout controllers, domain controllers and some view/gsp files for me.
Now for testing purpose I need to test one of the controller, so I have created one sample controller which is named as Secure with following code :
package com.springsecurity;
import grails.plugins.springsecurity.Secured;
class SecureController {
#Secured(['ROLE_ADMIN'])
def index = {
render 'Secure access only'
}
}
Now from the documentation I have found one step where it's showing me to create a default user and it's role from Bootstrap.groovy. So I have write the following piece of code in Bootstrap.groovy :
def adminRole = new SpringRole(authority: 'ROLE_ADMIN').save(flush: false)
def userRole = new SpringRole(authority: 'ROLE_USER').save(flush: false)
String password = springSecurityService.encodePassword('password')
def testUser = new SpringUser(username: 'me', enabled: true, password: password)
testUser.save(flush: false)
SpringUserSpringRole.create testUser, adminRole, true
assert SpringUser.count() == 1
assert SpringRole.count() == 2
assert SpringUserSpringRole.count() == 1
One thing I would like to know here is that I have not created any table yet in the backend. So is it required at this step or the above code will store the single user in the session ?
With above piece of code I am getting following exception at the time of running the project :
2010-11-11 11:42:47,932 [main] ERROR context.GrailsContextLoader - Error executing bootstraps: getFlushMode is not valid without active transaction
org.hibernate.HibernateException: getFlushMode is not valid without active transaction
at $Proxy16.getFlushMode(Unknown Source)
at BootStrap$_closure1.doCall(BootStrap.groovy:29)
at grails.util.Environment.evaluateEnvironmentSpecificBlock(Environment.java:251)
at grails.util.Environment.executeForEnvironment(Environment.java:244)
at grails.util.Environment.executeForCurrentEnvironment(Environment.java:220)
at org.grails.tomcat.TomcatServer.start(TomcatServer.groovy:164)
at grails.web.container.EmbeddableServer$start.call(Unknown Source)
at _GrailsRun_groovy$_run_closure5_closure12.doCall(_GrailsRun_groovy:158)
at _GrailsRun_groovy$_run_closure5_closure12.doCall(_GrailsRun_groovy)
at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:280)
at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy)
at _GrailsRun_groovy$_run_closure5.doCall(_GrailsRun_groovy:149)
at _GrailsRun_groovy$_run_closure5.call(_GrailsRun_groovy)
at _GrailsRun_groovy.runInline(_GrailsRun_groovy:116)
at _GrailsRun_groovy.this$4$runInline(_GrailsRun_groovy)
at _GrailsRun_groovy$_run_closure1.doCall(_GrailsRun_groovy:59)
at RunApp$_run_closure1.doCall(RunApp.groovy:33)
at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)
at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
at gant.Gant.withBuildListeners(Gant.groovy:427)
at gant.Gant.this$2$withBuildListeners(Gant.groovy)
at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
at gant.Gant.dispatch(Gant.groovy:415)
at gant.Gant.this$2$dispatch(Gant.groovy)
at gant.Gant.invokeMethod(Gant.groovy)
at gant.Gant.executeTargets(Gant.groovy:590)
at gant.Gant.executeTargets(Gant.groovy:589)
Application context shutting down...
Application context shutdown.
After seeing the above error, I am feeling that it's actually trying to store the specified object (in Bootstrap.groovy) to database and there is no table so it's throwing some exception.
Any help would be highly appreciated...
Thanks in advance..
The error message is "getFlushMode is not valid without active transaction" which doesn't have anything to do with whether there are tables or not.
If you're using dbCreate=create-drop or dbCreate=update in DataSource.groovy then all of the tables for your domain classes will be created for you. If you've disabled dbCreate then yes, you'll need to create the associated tables, but this is necessary any time you add one or more domain classes to a Grails app.
Looking at the Grails User mailing list it looks like this is a jar file conflict from something you added to your lib directory or something added by another plugin. One user found that Drools 4.0 was the problem when he saw this error. Do you have plugins that include Hibernate jars, or other libraries that Hibernate depends on, e.g. Antlr?
Got it finally...
Just commented following line in hibernate.cfg.xml
<property name="current_session_context_class">thread</property>
Not sure if you saw this but there is a pretty detailed walkthrough on how to do this here:
http://blog.springsource.com/2010/08/11/simplified-spring-security-with-grails/
Specifically it seems that your hibernate code is not contained within a hibernate session (which your test code probably is not setting up properly) and thus the error message. Typically you want to configure hibernate with hibernate.hbm2ddl.auto to have it auto-create tables and such.
For more information on hibernate.hbm2ddl.auto you can look here:
Hibernate hbm2ddl.auto possible values and what they do?
Grant

Resources