Showing posts with label Authentication. Show all posts
Showing posts with label Authentication. Show all posts

Points To Remember


  1. You must have a project created in Developers console to use Youtube data api and other api's.
  2. You should save the youtube refresh token in a database or file where you can save it for a long time and use it.
  3. Youtube refresh token is generated only once, so if you want to regenerate it go to google accounts page and revoke access to your project and then re authenticate.
  4. To revoke access, go to Connected Apps and Sites in the above mentioned url and click on your project and then click revoke access to revoke access to the app.

Steps to Use Youtube Data Api v3

  1. You need to create a new Project in your at Developers Console.
  2. After creating a project you need to go to Project -> Api & auth -> Credentials , and then create a new Client ID.
  3. Go to Project -> Api & auth ->APIs and enable Youtube Analytics API and YouTube Data API v3. This will enable your project to use consume these api's.
  4. For using these api's in your application you need to setup the callback url. Go to Project -> Api & auth ->API -> Credentials
  5. You are all ready to use the youtube data api.
 In this tutorial we will see how to use the youtube data api in Grails. See how to use Youtube data api in Java example.

Add Rest Plugin to your project

BuildConfig.groovy
Add the following dependency to your project BuildConfig to enable rest calls using HttpBuilder.
compile ":rest:0.8"


Config.groovy
Save your data in the Config and use it in database, config used in this example is given below.
youtube{

clientId="your_client_id"
clientSecret="your_client_secret"
scope ="https://gdata.youtube.com"
responseType ="code"
accessType="offline"
redirectUrl = "http://localhost:8085/youtube/callBack"

url{
auth = "https://accounts.google.com/o/oauth2/auth"
token = "https://accounts.google.com/o/oauth2/token"
userInfo = "https://www.googleapis.com/oauth2/v2/userinfo"
dataApi = "https://www.googleapis.com/youtube/v3"
}

}

Use Youtube Data Api v3

YoutubeController.groovy
Use this controller to authenticate the user from the google account and use youtube api. You should implement the logic to save the response data i.e. refresh token in database.
class YoutubeController {


YoutubeAuthService youtubeAuthService


def auth(){
response.sendRedirect(youtubeAuthService.createAuthorizeRequest());
}

def callBack(String code){
// User did not rejected authorization of your project
if(!code)
redirect(action: 'Error Action')
def object = youtubeAuthService.getAccessToken(code)

// Save your Youtube Tokens to DB
// or hit data api to get User info using access token and then save
 
// chain the request to your success handler.
chain(controller: 'controller', action: 'action')
}
}

YoutubeAuthService.groovy
Use this service to get the access token and refresh tokens
package com.ekiras.youtube

import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method

import static groovyx.net.http.ContentType.URLENC

class YoutubeAuthService {

def grailsApplication


String createAuthorizeRequest() {
String clientId = grailsApplication.config.youtube.clientId;
String authUrl = grailsApplication.config.youtube.url.auth;
String redirectUrl = grailsApplication.config.youtube.redirectUrl;
String scope = grailsApplication.config.youtube.scope;
String responseType = grailsApplication.config.youtube.responseType;
String accessType = grailsApplication.config.youtube.accessType;

String authRequest = authUrl + "?client_id=" + clientId + "&redirect_uri=" + redirectUrl + "&scope=" + scope + "&response_type=" + responseType + "&access_type=" + accessType
return authRequest;
}

def getAccessToken(String code){

String clientId = grailsApplication.config.youtube.clientId;
String clientSecret = grailsApplication.config.youtube.clientSecret;
String tokenRequestUrl = grailsApplication.config.youtube.url.token;
String redirectUrl = grailsApplication.config.youtube.redirectUrl;
String grantType = "authorization_code";

Map data = ['client_id':clientId,'client_secret':clientSecret,'code':code ,'redirect_uri':redirectUrl,'grant_type':grantType]
HTTPBuilder httpBuilder = new HTTPBuilder(tokenRequestUrl);

httpBuilder.request(Method.POST){
requestContentType = URLENC
body = data;
response.success = {resp, reader ->
// reader contains a access_token,token_type and expires_in
return reader
}
response.failure = {response, reader ->
return null
}
}
}

}

Points To Remember

  • You need to have a SSL certificate o run an application/ server on https.
  • You can create a SSL certificate using keytool.
  • The keystore file for Java is available in Java/jre/lib/security/cacerts.
  • Default password of the keystore is "changeit".

Create a Keystore

You can make a SSL certificate by following the steps below.
  1. Open a Command-line or Terminal window and make sure you're in your home directory.
  2. Execute the following command in the terminal
    keytool -genkey -alias tomcat -keyalg RSA -validity 365
    NOTE, the validity parameter allows you to specify, in the number of days, how long the certificate should be valid for. The longer the time period, the less likely you are to need to recreate it. To recreate it, you'd need to delete the old one and then follow these instructions again.
  3. The response will look something like this:
    Enter keystore password: 
    Re-enter new password:
    What is your first and last name?
    [Unknown]: $MACHINE_NAME
    What is the name of your organizational unit?
    [Unknown]: Test
    What is the name of your organization?
    [Unknown]: Test
    What is the name of your City or Locality?
    [Unknown]: Test
    What is the name of your State or Province?
    [Unknown]: Test
    What is the two-letter country code for this unit?
    [Unknown]: US
    Is CN=$FULL_MACHINE_NAME, OU=Test, O=Test, L=Test, ST=Test, C=IN correct?
    [no]: yes
    For the keystore password you should enter "changeit" without the quotation marks.
The above steps will successfully create a keystore file by name .keystore in the home directory.

Create a Server Certificate 

Any application that wishes to securely connect to the Tomcat instance would need to import the certificate. You can export the certificate that's compatible with other JVM keystores by executing the following command:
keytool -export -alias tomcat -file server.crt

Adding Server Certificate to JVM keystore

You will now have to import the server.crt file created in the last step to the jvm's keystore, you can do it by following command.
keytool -import -file server.crt -keystore $JAVA_HOME/jre/lib/security/cacerts -alias tomcat
You need to provide the password of your keystore( default password is "changeit") to successfully import the server.crt file to the jvm cacerts.

Useful Command for using keystore.

  1. Check all the certificates added to the keystore.
    keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts -v
  2. Delete any certificate from keystore.
    keytool -delete -noprompt -alias ${certificate.alias}  -keystore ${keystore.file}
  3. Add a certificate to the keystore.
    keytool -export -alias tomcat -file ${server.crt}
  4. Change Java Keystore Password.
    keytool -storepasswd -new new_storepass -keystore keystore.jks
How to configure tomcat to run on HTTPS

Points To Remember

Program : Test CAS Rest Api from a Java Code

You can use the following piece of code to test the CAS Rest API.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

public class TestCASRest {


public static void main(String... args) throws Exception
{
String username ="ekansh@ekiras.com";
String password ="password";
validateFromCAS(username,password);
}

public static boolean validateFromCAS(String username, String password) throws Exception
{

String url = "https://ekansh:8443/cas/v1/tickets";
try
{
HttpsURLConnection hsu = (HttpsURLConnection)openConn(url);
String s = URLEncoder.encode("username","UTF-8") + "=" + URLEncoder.encode(username,"UTF-8");
s+="&" +URLEncoder.encode("password","UTF-8") + "=" + URLEncoder.encode(password,"UTF-8");

System.out.println("string s = "+s);
OutputStreamWriter out = new OutputStreamWriter(hsu.getOutputStream());
BufferedWriter bwr = new BufferedWriter(out);
bwr.write(s);
bwr.flush();
bwr.close();
out.close();

String tgt = hsu.getHeaderField("location");
System.out.println( hsu.getResponseCode());
if(tgt != null && hsu.getResponseCode() == 201)
{
System.out.println(tgt);

System.out.println("Tgt is : " + tgt.substring( tgt.lastIndexOf("/") +1));
tgt = tgt.substring( tgt.lastIndexOf("/") +1);
bwr.close();
closeConn(hsu);


String serviceURL = "http://ekansh:8090/";
String encodedServiceURL = URLEncoder.encode("service","utf-8") +"=" + URLEncoder.encode(serviceURL,"utf-8");
System.out.println("Service url is : " + encodedServiceURL);



String myURL = url+ "/"+ tgt ;
System.out.println(myURL);
hsu = (HttpsURLConnection)openConn(myURL);
out = new OutputStreamWriter(hsu.getOutputStream());
bwr = new BufferedWriter(out);
bwr.write(encodedServiceURL);
bwr.flush();
bwr.close();
out.close();

System.out.println("Response code is: " + hsu.getResponseCode());

BufferedReader isr = new BufferedReader( new InputStreamReader(hsu.getInputStream()));
String line;
System.out.println( hsu.getResponseCode());
while ((line = isr.readLine()) != null) {
System.out.println( line);
}
isr.close();
hsu.disconnect();
return true;

}
else
{
return false;
}


}
catch(MalformedURLException mue)
{
mue.printStackTrace();
throw mue;

}
catch(IOException ioe)
{
ioe.printStackTrace();
throw ioe;
}





}


static URLConnection openConn(String urlk) throws MalformedURLException, IOException
{

URL url = new URL(urlk);
HttpsURLConnection hsu = (HttpsURLConnection) url.openConnection();
hsu.setDoInput(true);
hsu.setDoOutput(true);
hsu.setRequestMethod("POST");
return hsu;


}


static void closeConn(HttpsURLConnection c)
{
c.disconnect();
}


}
You will get the following type of response if everything is working fine.
string s = username=admin%40gmail.com&password=igdefault
201
https://ekansh:8443/cas/v1/tickets/TGT-3-eeSgMb35iv3TkqYzqekyhjZcGyNwKKq2s94reeoRINtdKJBvjx-ekansh
Tgt is : TGT-3-eeSgMb35iv3TkqYzqekyhjZcGyNwKKq2s94reeoRINtdKJBvjx-ekansh
Service url is : service=http%3A%2F%2Fekansh%3A8090%2F
https://ekansh:8443/cas/v1/tickets/TGT-3-eeSgMb35iv3TkqYzqekyhjZcGyNwKKq2s94reeoRINtdKJBvjx-ekansh
Response code is: 200
200
ST-3-Uagfse2pVB7hR5GL09WB-ekansh
If the authentication fails at the server then you will get a response like the following
string s = username=ekansh%40ekiras.com&password=pwd
400
TGT - It is the token by the ticket granting token.
ST-3-Uagfse2pVB7hR5GL09WB-ekansh - It is the service token.

Points To Remember

Step 1: Adding dependency in pom.xml

First thing that we need to do here is to add the CAS Rest Api dependencies to pom.xml so that we can get the related jars in the class path.
 <dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-integration-restlet</artifactId>
<version>${cas.version}</version>
<type>jar</type>
</dependency>
Note : Here we are using CAS v4.0.0

Step 2: Mapping Servlet in web.xml

Now, we need to map the restlet servlet in the web.xml. For this copy the previously generated web.xml from the war file and add the following lines in the web.xml file. This will register the servlet and the url pattern with which this servlet can be accessed. Here we are using v1/* as the url mapping, you can customize it according to your use case.
  <servlet>
<servlet-name>restlet</servlet-name>
<servlet-class>org.restlet.ext.spring.RestletFrameworkServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>restlet</servlet-name>
<url-pattern>/v1/*</url-pattern>
</servlet-mapping>

Step 3 : Create war file

Create the war file using maven command
mvn clean package
This will create a war file, upload this war file on servlet container, tomcat for our case. Restart the tomcat server and launch the application.

Step 4 : Test our CAS rest application

  1. When you launch the application you will see the cas login screen. 
  2. Enter the username and password we created in the database in this blog (username = ekansh@ekiras.com, password = password).
  3. You will see the login success screen.
    CAS -  Login success screen
  4. Now, enter the url /cas/v1/tickets. You should see the following page.
    CAS - Rest api url = cas/vi/tickets/
    If you can see this page you are done configuring the CAS Rest API. 
You are seeing this page because this rest api, expects a POST method call and by hitting the url from browser we are giving a GET request.


Points To Remember
  • You can user MYSQL, Oracle or PostgreSQL connectors as the database.
  • Make sure you have created a SSL certificate to run the CAS server on browser.

Step 1: Adding Dependencies in pom.xml

Add the following dependencies to the pom.xml that we created in this tutorial. These are the dependencies that are required to authenticate the user using the database.
 <dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-support-generic</artifactId>
<version>${cas.version}</version>
<type>jar</type>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-support-jdbc</artifactId>
<version>${cas.version}</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-integration-restlet</artifactId>
<version>${cas.version}</version>
<type>jar</type>
</dependency>
So now the pom.xml will look like the following
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd ">
<modelVersion>4.0.0</modelVersion>
<groupId>cas</groupId>
<artifactId>ekiras</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>

<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>cas</warName>
</configuration>
</plugin>
</plugins>
</build>

<dependencies>
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-webapp</artifactId>
<version>${cas.version}</version>
<type>war</type>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-support-generic</artifactId>
<version>${cas.version}</version>
<type>jar</type>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-support-jdbc</artifactId>
<version>${cas.version}</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-integration-restlet</artifactId>
<version>${cas.version}</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
</dependencies>

<properties>
<cas.version>4.0.0</cas.version>
</properties>

<repositories>
<repository>
<id>ja-sig</id>
<url>http://oss.sonatype.org/content/repositories/releases/ </url>
</repository>
</repositories>
</project>
Step 2: Configuring the deployerConfigContext.xml
Create folder /src/main/webapp/WEB-INF in the directory PROJECT. Now create a file named deployerConfigContext.xml in this folder location. and add the following configurations.
<?xml version="1.0" encoding="UTF-8"?>
<!--

Licensed to Jasig under one or more contributor license
agreements. See the NOTICE file distributed with this work
for additional information regarding copyright ownership.
Jasig licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a
copy of the License at the following location:

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.

-->
<!--
| deployerConfigContext.xml centralizes into one file some of the declarative configuration that
| all CAS deployers will need to modify.
|
| This file declares some of the Spring-managed JavaBeans that make up a CAS deployment.
| The beans declared in this file are instantiated at context initialization time by the Spring
| ContextLoaderListener declared in web.xml. It finds this file because this
| file is among those declared in the context parameter "contextConfigLocation".
|
| By far the most common change you will need to make in this file is to change the last bean
| declaration to replace the default authentication handler with
| one implementing your approach for authenticating usernames and passwords.
+-->

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<!--
| The authentication manager defines security policy for authentication by specifying at a minimum
| the authentication handlers that will be used to authenticate credential. While the AuthenticationManager
| interface supports plugging in another implementation, the default PolicyBasedAuthenticationManager should
| be sufficient in most cases.
+-->
<bean id="authenticationManager" class="org.jasig.cas.authentication.PolicyBasedAuthenticationManager">
<constructor-arg>
<map>
<!--
| IMPORTANT
| Every handler requires a unique name.
| If more than one instance of the same handler class is configured, you must explicitly
| set its name to something other than its default name (typically the simple class name).
-->
<entry key-ref="proxyAuthenticationHandler" value-ref="proxyPrincipalResolver" />
<!--entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" /-->
<entry key-ref="SearchModeSearchDatabaseAuthenticationHandler" value-ref="proxyPrincipalResolver" />
</map>
</constructor-arg>

<!-- Uncomment the metadata populator to allow clearpass to capture and cache the password
This switch effectively will turn on clearpass.
<property name="authenticationMetaDataPopulators">
<util:list>
<bean class="org.jasig.cas.extension.clearpass.CacheCredentialsMetaDataPopulator"
c:credentialCache-ref="encryptedMap" />
</util:list>
</property>
-->

<!--
| Defines the security policy around authentication. Some alternative policies that ship with CAS:
|
| * NotPreventedAuthenticationPolicy - all credential must either pass or fail authentication
| * AllAuthenticationPolicy - all presented credential must be authenticated successfully
| * RequiredHandlerAuthenticationPolicy - specifies a handler that must authenticate its credential to pass
-->
<property name="authenticationPolicy">
<bean class="org.jasig.cas.authentication.AnyAuthenticationPolicy" />
</property>
</bean>

<!-- Required for proxy ticket mechanism. -->
<bean id="proxyAuthenticationHandler"
class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"
p:httpClient-ref="httpClient" />

<!--
| TODO: Replace this component with one suitable for your enviroment.
|
| This component provides authentication for the kind of credential used in your environment. In most cases
| credential is a username/password pair that lives in a system of record like an LDAP directory.
| The most common authentication handler beans:
|
| * org.jasig.cas.authentication.LdapAuthenticationHandler
| * org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler
| * org.jasig.cas.adaptors.x509.authentication.handler.support.X509CredentialsAuthenticationHandler
| * org.jasig.cas.support.spnego.authentication.handler.support.JCIFSSpnegoAuthenticationHandler
-->

<!-- Authentication method start-->

<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource"
p:driverClass="com.mysql.jdbc.Driver"
p:jdbcUrl="jdbc:mysql://localhost:3306/cas"
p:user="username"
p:password="password" />

<!-- Authentication method end-->
<bean id="passwordEncoder"
class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder"
c:encodingAlgorithm="MD5"
p:characterEncoding="UTF-8" />

<bean id="SearchModeSearchDatabaseAuthenticationHandler"
class="org.jasig.cas.adaptors.jdbc.SearchModeSearchDatabaseAuthenticationHandler"
p:dataSource-ref="dataSource"
p:passwordEncoder-ref="passwordEncoder"
p:tableUsers="user"
p:fieldUser="email"
p:fieldPassword="password" />

<!-- Required for proxy ticket mechanism -->
<bean id="proxyPrincipalResolver"
class="org.jasig.cas.authentication.principal.BasicPrincipalResolver" />

<!--
| Resolves a principal from a credential using an attribute repository that is configured to resolve
| against a deployer-specific store (e.g. LDAP).
-->
<bean id="primaryPrincipalResolver"
class="org.jasig.cas.authentication.principal.PersonDirectoryPrincipalResolver" >
<property name="attributeRepository" ref="attributeRepository" />
</bean>

<!--
Bean that defines the attributes that a service may return. This example uses the Stub/Mock version. A real implementation
may go against a database or LDAP server. The id should remain "attributeRepository" though.
+-->
<bean id="attributeRepository" class="org.jasig.services.persondir.support.StubPersonAttributeDao"
p:backingMap-ref="attrRepoBackingMap" />

<util:map id="attrRepoBackingMap">
<entry key="uid" value="uid" />
<entry key="eduPersonAffiliation" value="eduPersonAffiliation" />
<entry key="groupMembership" value="groupMembership" />
</util:map>

<!--
Sample, in-memory data store for the ServiceRegistry. A real implementation
would probably want to replace this with the JPA-backed ServiceRegistry DAO
The name of this bean should remain "serviceRegistryDao".
+-->
<bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl"
p:registeredServices-ref="registeredServicesList" />

<util:list id="registeredServicesList">
<bean class="org.jasig.cas.services.RegexRegisteredService"
p:id="0" p:name="HTTP and IMAP"
p:description="Allows HTTP(S) and IMAP(S) protocols"
p:serviceId="^(https?|imaps?)://.*"
p:evaluationOrder="10000001"
p:enabled="true"
p:allowedToProxy="true"
p:ssoEnabled="true"
/>


<!--
Use the following definition instead of the above to further restrict access
to services within your domain (including sub domains).
Note that example.com must be replaced with the domain you wish to permit.
This example also demonstrates the configuration of an attribute filter
that only allows for attributes whose length is 3.
-->
<!--
<bean class="org.jasig.cas.services.RegexRegisteredService">
<property name="id" value="1" />
<property name="name" value="HTTP and IMAP on example.com" />
<property name="description" value="Allows HTTP(S) and IMAP(S) protocols on example.com" />
<property name="serviceId" value="^(https?|imaps?)://([A-Za-z0-9_-]+\.)*example\.com/.*" />
<property name="evaluationOrder" value="0" />
<property name="attributeFilter">
<bean class="org.jasig.cas.services.support.RegisteredServiceRegexAttributeFilter" c:regex="^\w{3}$" />
</property>
</bean>
-->
</util:list>

<bean id="auditTrailManager" class="com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager" />

<bean id="healthCheckMonitor" class="org.jasig.cas.monitor.HealthCheckMonitor" p:monitors-ref="monitorsList" />

<util:list id="monitorsList">
<bean class="org.jasig.cas.monitor.MemoryMonitor" p:freeMemoryWarnThreshold="10" />
<!--
NOTE
The following ticket registries support SessionMonitor:
* DefaultTicketRegistry
* JpaTicketRegistry
Remove this monitor if you use an unsupported registry.
-->
<bean class="org.jasig.cas.monitor.SessionMonitor"
p:ticketRegistry-ref="ticketRegistry"
p:serviceTicketCountWarnThreshold="5000"
p:sessionCountWarnThreshold="100000" />
</util:list>
</beans>

Points to be noted here
  1. We have created a datasource bean
    <bean id="dataSource"
    class="com.mchange.v2.c3p0.ComboPooledDataSource"
    p:driverClass="com.mysql.jdbc.Driver"
    p:jdbcUrl="jdbc:mysql://localhost:3306/cas"
    p:user="username"
    p:password="password" />
    Here we can are using MYSQL database for authentication. This bean takes inputs like driver class, url, database username and password. You can add your database username password here.
  2. We have created a password encoder here via bean that encodes the password using MD5 encrption algorithm.
    <bean id="passwordEncoder"
    class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder"
    c:encodingAlgorithm="MD5"
    p:characterEncoding="UTF-8" />
    You can also use other password encoding algorithms here like SHA1.
  3. We have created SearchModeSearchDatabaseAuthenticationHandler bean, this will actually lookup the database and authenticate the user if found.
    <bean id="SearchModeSearchDatabaseAuthenticationHandler"
    class="org.jasig.cas.adaptors.jdbc.SearchModeSearchDatabaseAuthenticationHandler"
    p:dataSource-ref="dataSource"
    p:passwordEncoder-ref="passwordEncoder"
    p:tableUsers="user"
    p:fieldUser="email"
    p:fieldPassword="password" />
    This is the code that tells the CAS server to look for user in database via datasource that we have declared in in point 1 above. This also includes the password encoder to encode the password before checking in the database. TableUsers is the table it will look, fieldUser is the username that will be checked and fieldPassword is the password that will be looked for. Here we are making user login with email and password.
Step 3: Create Dummy Table with values..
create table user(
id int primary key auto_increment,
email varchar(255),
password varchar(255));
This will create the table as
+-------------+----------------+-------+------+-----------+--------------------+
| Field          | Type            | Null  | Key | Default | Extra                   |
+-------------+----------------+-------+------+-----------+--------------------+
| id               | int(11)          | NO    | PRI | NULL    | auto_increment |
| email         | varchar(255) | YES |        | NULL    |                           |
| password  | varchar(255) | YES  |        | NULL    |                          |
+-------------+----------------+--------+------+-----------+-------------------+
Now lets insert dummy values
insert into user(email,password) values('ekansh@ekiras.com','5f4dcc3b5aa765d61d8327deb882cf99')
Here '5f4dcc3b5aa765d61d8327deb882cf99' is the MD5 conversion of the string password.
Step 4: Testing our CAS server war.
Lets create the war using the following command.
mvn clean package
Now we go and deploy the war as instructed here. We will get the CAS login screen and we can enter the dummy email and password we have in database to login (email='ekansh@ekiras.com', password = 'password'). This will successfully log the user into the CAS server.

Points To Remember
  • CAS works on Maven WAR overlay technique.
  • You need to create a SSL certificate to use CAS and run it over https to enable SSO(single sign on). How to create a SSL certificate and add it to keystore.
  • You can use LDAP, Database and Active Directory techniques to authenticate the user.
Requirements
  1. You need to have Java SDK v1.6 or greater.
  2. Servlet Containers like Tomcat , Websphere, JBoss etc. 
  3. Apache Maven v3.0 or greater.
  4. Authentication technique related dependencies.
For the sake of simplicity let us assume that out application path is
PROJECT = /home/ekiras/cas
and our tomcat path is
TOMCAT = /home/ekiras/apache

Step 1 : Create pom.xml
You need to create a pom.xml to create the war file and package it. lets create the pom file in the project directory i.e. PROJECT/pom.xml
Add the following code to the pom.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd ">
<modelVersion>4.0.0</modelVersion>
<groupId>cas</groupId>
<artifactId>ekiras</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>

<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>cas</warName>
</configuration>
</plugin>
</plugins>
</build>

<dependencies>
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-webapp</artifactId>
<version>${cas.version}</version>
<type>war</type>
<scope>runtime</scope>
</dependency>
</dependencies>

<properties>
<cas.version>4.0.0</cas.version>
</properties>

<repositories>
<repository>
<id>ja-sig</id>
<url>http://oss.sonatype.org/content/repositories/releases/ </url>
</repository>
</repositories>
</project>
Here we have added the dependencies of the project and the repositories where it will look for the dependencies and jars. We are setting up CAS version 4.0.0
Step 2 : Lets check our progress
Let us check our progress and see if we have not missed on something. Run the following command
mvn clean package
This will create a war file in the directory PROJECT/target/. Deploy this war file on tomcat as instructed here. Now run the app you will see the screen like the following.
CAS login screen
You can now login to the CAS server using username="casuser" and password="Mellon". These are the default username password that can be used to login. After login you will see the screen like the following.
CAS Successful Login screen
We can logout the cas server using the path /logout. This will log out the user.
CAS successful logout screen.
So, we have now setup our CAS server and successfully logged into and logged out of  the CAS server.

How to Use Database for CAS Authentication.