自定义Tomcat Realm。

tomaer 发布于 2011/01/13 18:40
阅读 476
收藏 4

给一个思路,你可以随意扩展,废话不多说.上代码.欢迎仍鸡蛋..配置部分和DatasourceRealm一样,只是将实现类改成自定义的即可

package com.tomaer.realm;

import java.security.Principal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

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

/**
 * <pre>
 * 		This is an extension of tomcat DataSourceRealm @see org.apache.catalina.realm.DataSourceRealm 
 * 		Allows the use of the standard
 * 		Realm login and a login method based FacebookId
 * </pre>
 * @author tomaer creaeted on 2011-01-13
 * 
 * 
 */
public class PortalRealm extends DataSourceRealm {

	private static final String FACEBOOK_ACCOUNT_PREFIX = "facebook.com.userId-";

	/**
	 * <pre>
	 * 	This method will automatically determine the value passed in the j_username, 
	 * 	if it is consistent with the format of predefined FacebookId,
	 * 	This property will be based on FACEBOOK_ID query to the corresponding USER_ID
	 *  Then the role of the corresponding USER_ID query,Finally, construct a Principal object,
	 *  On the contrary, will call super authenticate method
	 * 		
	 * </pre>
	 */
	@Override
	public Principal authenticate(String username, String credentials) {
		if (username == null) {
			return null;
		}
		if (
				username.trim().indexOf(FACEBOOK_ACCOUNT_PREFIX) != -1 
				&& 
				username.trim().length() > FACEBOOK_ACCOUNT_PREFIX.length() 
			) {
			String userId = "";
			Connection conn = open();
			PreparedStatement pst = null;
			ResultSet rs = null;
			String sql = "SELECT USER_ID FROM USERS WHERE FACEBOOK_ID = ?";
			try {
				pst = conn.prepareStatement(sql);
				pst.setString(1, getFacebookId(username));
				rs = pst.executeQuery();
				if (rs.next()) {
					userId = rs.getString(1);
				} else {
					return null;
				}
			} catch (SQLException e) {
				this.containerLog.error("Get USER_ID by FACEBOOK_ID exception",e);
				return null;
			}
			ArrayList<String> roles = new ArrayList<String>();
			sql = "SELECT ROLE_NAME FROM USER_ROLES WHERE USER_ID = ?";
			try {
				pst = conn.prepareStatement(sql);
				pst.setString(1, userId);
				pst = conn.prepareStatement(sql);
				pst.setString(1, userId.trim());
				rs = pst.executeQuery();
				while (rs.next()) {
					String role = rs.getString(1);
					if (role != null) {
						roles.add(role);
					}
				}
			} catch (SQLException e) {
				this.containerLog.error("Get USER_ID by FACEBOOK_ID exception",e);
				return null;
			} finally {
				close(conn);
			}
			return new GenericPrincipal(this, userId, null, roles);
		} else {
			return super.authenticate(username, credentials);
		}
	}

	private static String getFacebookId(String username) {
		if (username.length() == FACEBOOK_ACCOUNT_PREFIX.length()) {
			return "";
		}
		return username.substring(FACEBOOK_ACCOUNT_PREFIX.length());
	}
}
加载中
0
红薯
红薯

建议将这种代码类的内容发到代码分享中:)

返回顶部
顶部