Search code examples
javaspring-mvcencryptionspring-securitykeystore

Spring MVC : Using User password to create a Java keystore, and access keys later


  • I am working on a Spring-MVC application in which there is a Person class for whom I am storing the password in database with BCrypt format. Now, I would like to create a Java keystore using MD5 sum of the user's plaintext password.
    • But because I don't know how and where Spring-security is taking the plaintext password and doing a BCrypt on it to check vs the database, I am not able to use the plaintext password to create an MD5 sum.
    • And this process I would like to repeat everytime the user logs in so that I can unlock the keystore programmatically and retrieve the key with keyname and the MD5 sum as the password.

I am pasting my Person model and, spring-security-application.xml :

 @Entity
@Table(name="person")
public class Person implements UserDetails{

    private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER");

    private static final String emailRegexp = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";

    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "person_seq_gen")
    @SequenceGenerator(name = "person_seq_gen",sequenceName = "person_seq")
    private int id;

    @Valid
    @Email
    @Pattern(regexp = emailRegexp)
    @Column(name = "username")
    private String username;

    @Valid
    @NotEmpty(message = "Password may not be empty")
    @Column(name = "password")
    private String password;


 //getters and setters ommitted

}

PersonServiceImpl :

 @Override
    @Transactional
    public boolean addPerson(Person p) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Person existingUser = personDAO.findPersonByUsername(p.getUsername());
        if(existingUser == null) {
            this.personDAO.addPerson(p);
            p.setAccountstatus(false);
            p.setOnetimeemail(false);
            p.setUsername(p.getUsername().toLowerCase());
            p.setPassword(BCrypt.hashpw(p.getPassword(), BCrypt.gensalt(11)));
            p.setUsername(p.getUsername().toLowerCase());
            this.personDAO.addPerson(p);
            sendAccountActivationEmail(p.getUsername(), p.getFirstName());
            return true;
        } else {
            return  false;
        }
    }

security-applicationContext.xml :

 <security:global-method-security pre-post-annotations="enabled" />

    <security:http create-session="ifRequired" use-expressions="true" auto-config="true" disable-url-rewriting="true">
        <security:form-login login-page="/login" default-target-url="/canvas/list" always-use-default-target="false" authentication-failure-url="/denied.jsp" />
        <security:remember-me key="_spring_security_remember_me" user-service-ref="userDetailsService" token-validity-seconds="1209600" data-source-ref="dataSource"/>
        <security:logout delete-cookies="JSESSIONID" invalidate-session="true" logout-url="/j_spring_security_logout"/>

<!--        <security:intercept-url pattern="/**" requires-channel="https"/> -->

  <!--  <security:port-mappings>
        <security:port-mapping http="80" https="443"/>
    </security:port-mappings>
-->
    </security:http>




    <!-- queries to be run on data -->
    <beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
        <beans:property name="key" value="_spring_security_remember_me" />
        <beans:property name="tokenRepository" ref="jdbcTokenRepository"/>
        <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
    </beans:bean>

    <!--Database management for remember-me -->
    <beans:bean id="jdbcTokenRepository"
                class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
        <beans:property name="createTableOnStartup" value="false"/>
        <beans:property name="dataSource" ref="dataSource" />
    </beans:bean>

    <!-- Remember me ends here -->
    <security:authentication-manager alias="authenticationManager" erase-credentials="false">
        <security:authentication-provider user-service-ref="LoginServiceImpl">
           <security:password-encoder  ref="encoder"/>
        </security:authentication-provider>
    </security:authentication-manager>

    <beans:bean id="encoder"
                class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <beans:constructor-arg name="strength" value="11" />
    </beans:bean>

    <beans:bean id="daoAuthenticationProvider"
                class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
                <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
<security:global-method-security pre-post-annotations="enabled" />

<security:http create-session="ifRequired" use-expressions="true" auto-config="true" disable-url-rewriting="true">
    <security:form-login login-page="/login" default-target-url="/canvas/list" always-use-default-target="false" authentication-failure-url="/denied.jsp" />
    <security:remember-me key="_spring_security_remember_me" user-service-ref="userDetailsService" token-validity-seconds="1209600" data-source-ref="dataSource"/>
    <security:logout delete-cookies="JSESSIONID" invalidate-session="true" logout-url="/j_spring_security_logout"/>
</security:http>

<beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
    <beans:property name="key" value="_spring_security_remember_me" />
    <beans:property name="tokenRepository" ref="jdbcTokenRepository"/>
    <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
</beans:bean>
<beans:bean id="jdbcTokenRepository"
            class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
    <beans:property name="createTableOnStartup" value="false"/>
    <beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<security:authentication-manager alias="authenticationManager" erase-credentials="false">
    <security:authentication-provider user-service-ref="LoginServiceImpl">
       <security:password-encoder  ref="encoder"/>
    </security:authentication-provider>
</security:authentication-manager>

<beans:bean id="encoder"
            class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
    <beans:constructor-arg name="strength" value="11" />
</beans:bean>

<beans:bean id="daoAuthenticationProvider"
            class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
            <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
           <beans:property name="passwordEncoder" ref="encoder"/>
</beans:bean>
            <beans:property name="passwordEncoder" ref="encoder"/>
    </beans:bean>

LoginServiceImpl :

@Transactional
@Service("userDetailsService")
public class LoginServiceImpl implements UserDetailsService{

    @Autowired private PersonDAO personDAO;
    @Autowired private Assembler assembler;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,DataAccessException {
        Person person = personDAO.findPersonByUsername(username.toLowerCase());
            if(person == null) { throw new UsernameNotFoundException("Wrong username or password");} //Never specify which one was it exactly
        return assembler.buildUserFromUserEntity(person);
    }

    public LoginServiceImpl() {
    }
}

Assembler :

@Service("assembler")
public class Assembler {
    @Transactional(readOnly = true)
    User buildUserFromUserEntity(Person userEntity){
        String username = userEntity.getUsername().toLowerCase();
        String password = userEntity.getPassword();

        boolean enabled = userEntity.isEnabled();
        boolean accountNonExpired = userEntity.isAccountNonExpired();
        boolean credentialsNonExpired = userEntity.isCredentialsNonExpired();
        boolean accountNonLocked = userEntity.isAccountNonLocked();

        Collection<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

        return new User(username,password,enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,authorities);
        }
}

I hope what I said was clear, if there are any doubts, kindly let me know.. Any help would be nice. Thanks a lot... :-)


Solution

  • You can let Spring Security keep the password in the session:

    <authentication-manager alias="authenticationManager" erase-credentials="false">
      <!-- authentication provider(s) -->
    </authentication-manager>
    

    Then you can retrieve the password by using:

    Authentication currentAuth = ...;
    String pwd = currentAuth.getCredentials().toString();
    

    To catch when user logins, you can listen for AuthenticationSuccessEvent.