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博客 ” ,链接:https://blog.itpub.net/301743/viewspace-731263/
,如需转载,请注明出处,否则将追究法律责任。