Tomcat security realm with MongoDB

jieforest發表於2012-05-28
Security Realms is a  Tomcat's build in feature for protecting web application resoureces.Amongthe many types of security realms there's one that uses a normal realtional database for userauthentication (JDBCRealm).In this tutorial we will see how to make a realm that uses mongoDBinstead of a relational database.

As a first step we must define the realm class.for further information on DAO objects see Integrate MongoDB into java web applications.

CODE:

package com.javaonlymongoDB.realm;

import com.javaonlymongoDB.daos.DaoFactory;
import com.javaonlymongoDB.daos.RoleDao;
import com.javaonlymongoDB.daos.UserDao;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import org.apache.catalina.realm.GenericPrincipal;
import org.apache.catalina.realm.RealmBase;

public class MongoRealm extends RealmBase {

  @Override
  protected String getName() {
    return this.getClass().getSimpleName();
  }

  @Override
  protected String getPassword(final String username) {
      String password="";
      UserDao userDao = DaoFactory.getUserDao();
        DBCursor all = userDao.getPassword(username);
        while (all.hasNext()) {
            DBObject bject = all.next();
            password= (String) object.get("password");
            System.out.println("NAAMEEE:" + password);
        }
    return password;
  }

  @Override
  protected Principal getPrincipal(final String username) {
      String name = "";
final List roles = new ArrayList();
  RoleDao roleDao = DaoFactory.getRoleDao();
  DBCursor all = roleDao.getRole(username);
  while (all.hasNext()) {
       DBObject bject = all.next();
       name = (String) object.get("role_name");
  }
  String password = "";
  UserDao userDao = DaoFactory.getUserDao();
  DBCursor al = userDao.getPassword(username);
  while (al.hasNext()) {
      DBObject bject = al.next();
      password= (String) object.get("password");
  }
  roles.add(name);
  return new GenericPrincipal(this, username, password, roles);
}
}  

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-731263/,如需轉載,請註明出處,否則將追究法律責任。

相關文章