Pages

Tuesday, April 17, 2012

Tomcat Authentication using Custom Realm

1. My web.xml

Set the security constraint in web.xml.

I want only admin to access my resources. I also wanted to use CustomRealm to be used.


"

Wildcard means whole app requires authentication
/*
GET
POST



admin






BASIC
CustomRealm
"


2. In tomcat's Server.xml, comment out the default Realm, and add your Custom Realm.



     


3. Create the custom Realm class/ project and place it under Lib folder of Tomcat.
Tomcat should see this CustomRealm when it starts up. If it doesn't see, it will complain. If everything goes good, you will wont see any error msg when starting up.



My CustomRealm class


public class CustomRealm extends RealmBase {

String username;
String password;

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

/*
* (non-Javadoc)
*
* @see org.apache.catalina.realm.RealmBase#getName()
*/
@Override
protected String getName() {
// TODO Auto-generated method stub
return null;
}

/*
* (non-Javadoc)
*
* @see org.apache.catalina.realm.RealmBase#getPassword(java.lang.String)
*/
@Override
protected String getPassword(String arg0) {
// TODO Auto-generated method stub
return null;
}

/*
* (non-Javadoc)
*
* @see org.apache.catalina.realm.RealmBase#getPrincipal(java.lang.String)
*/
@Override
protected Principal getPrincipal(String arg0) {


java.util.List roles = new ArrayList();
roles.add("admin");
return new GenericPrincipal(username, password, roles);

}

@Override
public Principal authenticate(String username, String password) {


try {

Debug.println(CustomRealm.class.getName(), "Authenticating with username : " + username
+ ", password : " + password);

setUsername(username);
setPassword(password);
String hashedPassword = AuthHelper.getHashedPassword(password
+ username);

Connection conn = AuthHelper.getConnection();
//If auth is success
if (AuthHelper.authenticate(username, hashedPassword, conn)) {

return getPrincipal(username);
} else
{
Debug.println(CustomRealm.class.getName(), "Auth failed");
//Tomcat will take care of denying the access
return null;
}

} catch (Exception e) {
//Some exception. We must deny the access.
e.printStackTrace();
Debug.println(CustomRealm.class.getName(), "Auth failed : " + e.getMessage() );

return null;
}

}

}


Important thing here is to return a Principal if auth succeeds. If not, fail. Also you need to note that you should add the role you defined in your web.xml.









No comments: