Saturday, August 23, 2014

Strategy Design Pattern

1) Create interface

interface SectionRemovalRule {

        void runRule(long userId) ;
    }

2) Create hashmap

private static Map<String, SectionRemovalRule> sectionRemovalMethodMap = new HashMap<String, SectionRemovalRule>();

3) Initialize map

 @PostConstruct
    void initSectionRemovalMethodMap() {

        sectionRemovalMethodMap.put("section1",
                new SectionRemovalRule() {
                    @Override
                    public void runRule(long sectionId)  {
                        section1Dao
                                .removeSection(sectionId);
                    }
                });

        sectionRemovalMethodMap.put("section2",
                new SectionRemovalRule() {
                 @Override
                    public void runRule(long sectionId)  {
                        section2Dao
                                .removeSection(sectionId);
                    }
                });
       
    }

4) Calling the method 

sectionRemovalMethodMap.get('yourSectionName').runRule(sectionId);

5) Benefits :

* It helps to avoid if else
* it makes code simple.
* increases performance

Spring Login Authentication

1) Configure password encoder bean 

<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>

2) configure salt source bean (optional)

  <beans:bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource"
        p:userPropertyToUse="username"/>

3) Configure rememberme bean

<beans:bean id="rememberMeAuthenticationProvider"
            class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
    <beans:constructor-arg value="e37f4b31-0c45-11dd-bd0b-0800200c9a66"/>
</beans:bean>


4) Configure authentication providers(list)

 <authentication-manager alias="authenticationManager">
    <authentication-provider ref="rememberMeAuthenticationProvider">
        </authentication-provider>
        <authentication-provider user-service-ref="userDao">
            <password-encoder ref="passwordEncoder" >
                <salt-source ref="saltSource" />
            </password-encoder>
        </authentication-provider>
        <authentication-provider ref="customAuthenticationProvider" />
    </authentication-manager>

5) Create class that implements userDao inteface and implement loadUserByUsername method

@Repository("userDao")
public class UserDaoHibernate extends GenericDaoHibernate<User, Long> implements
        UserDao, org.springframework.security.core.userdetails.UserDetailsService.UserDetailsService {

  UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{}

}

6) Create custom authentication provider 

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

@Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {

        String username = authentication.getName();
        String rawPassword = (String) authentication.getCredentials();

        User user = (User) userDao.loadUserByUsername(username);

        if (user == null) {
            throw new BadCredentialsException("Username not found.");
        }

        if (!passwordEncoder.isPasswordValid(encryptedPassword, rawPassword,
                saltField)) {
            throw new BadCredentialsException("Wrong password.");
        }

  
        Collection<? extends GrantedAuthority> authorities = user
                .getAuthorities();

        return new UsernamePasswordAuthenticationToken(user,
                user.getPassword(), authorities);
    }

  
    @Override
    public boolean supports(Class<?> arg0) {
            return true;
    }

}

7) Configure remember me filter for changing cookie name 

<beans:bean id="rememberMeServices"       class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
    <beans:constructor-arg value="e37f4b31-0c45-11dd-bd0b-0800200c9a66"/>
    <beans:constructor-arg ref="userDao"/>
    <beans:property name="cookieName" value="_SRM"/>
    </beans:bean>

<beans:bean id="rememberMeFilter"            class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
    <beans:constructor-arg ref="authenticationManager"/>
    <beans:constructor-arg ref="rememberMeServices"/>
</beans:bean>

Refer document for more information :  spring-security-document

Must read articles

configuring Tomcat to support SSL or https

1. Generate Keystore

First, uses “keytool” command to create a self-signed certificate. During the keystore creation process, you need to assign a password and fill in the certificate’s detail.
$Tomcat\bin>keytool -genkey -alias slc -keyalg RSA -keystore c:\keystore
Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  f
What is the name of your organizational unit?
  //omitted to save space
  [no]:  yes
 
Enter key password for <slc>
        (RETURN if same as keystore password):
Re-enter new password:
 
Certificate Details
 You can use same “keytool” command to list the existing certificate’s detail
$Tomcat\bin>keytool -list -keystore c:\keystore
Enter keystore password:   Keystore type: JKS Keystore provider: SUN   Your keystore contains 1 entry   slc, 14 Disember 2010, PrivateKeyEntry, Certificate fingerprint (MD5): C8:DD:A1:AF:9F:55:A0:7F:6E:98:10:DE:8C:63:1B:A5

2. Connector in server.xml

Next, locate your Tomcat’s server configuration file at $Tomcat\conf\server.xml, modify it by adding a connector element to support for SSL or https connection.
File : $Tomcat\conf\server.xml
 //...
 <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the 
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
 
 <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" 
        keystoreFile="c:\keystore"
        keystorePass="password" />

 

3 . Done

Saved it and restart Tomcat, access to https://localhost:8443/
 
 

4) Installing a Certificate from a Certificate Authority:

In order to obtain a Certificate from the Certificate Authority of your choice you have to create a so called Certificate Signing Request (CSR). That CSR will be used by the Certificate Authority to create a Certificate that will identify your website as "secure". To create a CSR follow these steps

 

  • Create a local Certificate (as described in the previous section):
    keytool -genkey -alias slc -keyalg RSA \
        -keystore <your_keystore_filename>
     
    Note: In some cases you will have to enter the domain of your website (i.e. www.myside.org) in the field "first- and lastname" in order to create a working Certificate. 

  • The CSR is then created with:
    keytool -certreq -keyalg RSA -alias slc -file certreq.csr \
        -keystore <your_keystore_filename>

 

Now you have a file called certreq.csr that you can submit to the Certificate Authority (look at the
documentation of the Certificate Authority website on how to do this). In return you get a Certificate.
 
Importing the Certificate
Now that you have your Certificate you can import it into you local keystore. First of all you have to import a so called Chain Certificate or Root Certificate into your keystore. After that you can proceed with importing your Certificate.
  • Download a Chain Certificate from the Certificate Authority you obtained the Certificate from.
    For Verisign.com commercial certificates go to: http://www.verisign.com/support/install/intermediate.html
    For Verisign.com trial certificates go to: http://www.verisign.com/support/verisign-intermediate-ca/Trial_Secure_Server_Root/index.html
    For Trustcenter.de go to: http://www.trustcenter.de/certservices/cacerts/en/en.htm#server
    For Thawte.com go to: http://www.thawte.com/certs/trustmap.html
  • Import the Chain Certificate into your keystore
    keytool -import -alias root -keystore <your_keystore_filename> \
        -trustcacerts -file <filename_of_the_chain_certificate>
  • And finally import your new Certificate
    keytool -import -alias tomcat -keystore <your_keystore_filename> \
        -file <your_certificate_filename>
 example:
 
<VirtualHost *:443>
    DocumentRoot "/vol/data/src/docRoot"
        ErrorLog logs/ssl_error_log
        TransferLog logs/ssl_access_log
        LogLevel warn
        SSLEngine on
        SSLProtocol all -SSLv2
        SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW
        SSLCertificateFile  /etc/httpd/conf.d/sslcert/self_signed/self-ssl.crt
        SSLCertificateKeyFile /etc/httpd/conf.d/sslcert/self_signed/self-ssl.key

  ServerName my.box.com
  RewriteEngine on

  DirectoryIndex index.html

  JkMount /myapp tomcat1
  JkMount /myapp/* tomcat1


        SetEnvIf User-Agent ".*MSIE.*" \
        nokeepalive ssl-unclean-shutdown \
        downgrade-1.0 force-response-1.0

        Alias /doc "/vol/data/src/doc/my_docs1/"
        <Directory /vol/data/src/doc/my_docs1/>
         Require all granted
         SSLRequireSSL
         Allow From all
         AllowOverride all

        </Directory>
</VirtualHost>
 
 
 

SOURCE : 

http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration