練功房推薦書單

  • 猛虎出柙雙劍合璧版--最新 OCA / OCP Java SE 7 Programmer 專業認證 (電子書)
  • 流浪教師存零股存到3000萬(全新增修版)(書+DVD)
  • 開始在關西自助旅行(京都‧大阪‧神戶‧奈良)(全新增訂版)
  • 不敗教主的300張股票存股術

JForum SSO with User's first name and last name saved RSS feed
討論區首頁 » JForum中文社群 JForum Chinese Users Community
發表人 內容
andowson

七段學員
[Avatar]

註冊時間: 2007/1/2
文章: 711
來自: 台北
離線
1.Add these two columns (first_name and last_name) into jforum_users table:

ALTER TABLE jforum_users ADD first_name VARCHAR(50);
ALTER TABLE jforum_users ADD last_name VARCHAR(50);

2.Add these keys to WEB-INF/config/jforum-custom.conf:

authentication.type=sso
sso.implementation=net.jforum.sso.MyUserSSO
sso.redirect=http\://member.andowson.com/sso/login.jsp
cookie.name.user=username
cookie.name.email=email
cookie.name.first=firstname
cookie.name.last=lastname
sso.firstname.attribute=firstname
sso.lastname.attribute=lastname
sso.default.firstname=Unknown
sso.default.lastname=User

member.andowson.com is where we are going to authenticate the user. Change to your real case.

3.Modify net.jforum.util.preferences.ConfigKeys.java:
Add these lines into ConfigKeys.java

public static final String SSO_FIRSTNAME_ATTRIBUTE = "sso.firstname.attribute";
public static final String SSO_LASTNAME_ATTRIBUTE = "sso.lastname.attribute";
public static final String SSO_DEFAULT_FIRSTNAME = "sso.default.firstname";
public static final String SSO_DEFAULT_LASTNAME = "sso.default.lastname";
public static final String COOKIE_NAME_EMAIL = "cookie.name.email";
public static final String COOKIE_NAME_FIRST = "cookie.name.first";
public static final String COOKIE_NAME_LAST = "cookie.name.last";

4.Add net.jforum.sso.MyUserSSO.java which implements net.jforum.sso.SSO interface

package net.jforum.sso;

import java.io.UnsupportedEncodingException;

import java.net.URLDecoder;
import javax.servlet.http.Cookie;
import net.jforum.context.RequestContext;
import net.jforum.context.SessionContext;
import net.jforum.ControllerUtils;
import net.jforum.JForumExecutionContext;
import net.jforum.entities.UserSession;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
import org.apache.log4j.Logger;

public class MyUserSSO implements SSO {

static final Logger logger = Logger.getLogger(CookieUserSSO.class.getName());

public String authenticateUser(RequestContext request) {
// myapp login cookie, contain logged username
Cookie myCookie = ControllerUtils.getCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_NAME_USER));
String username = null;
String email = null;
String firstName = null;
String lastName = null;

if (myCookie != null) {
username = myCookie.getValue();
}
SessionContext session = JForumExecutionContext.getRequest().getSessionContext();
String encoding = "Big5";
try {
myCookie = ControllerUtils.getCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_NAME_EMAIL));
if (myCookie != null) {
email = myCookie.getValue();
session.setAttribute(SystemGlobals.getValue(ConfigKeys.SSO_EMAIL_ATTRIBUTE), URLDecoder.decode(email, encoding));
}
myCookie = ControllerUtils.getCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_NAME_FIRST));
if (myCookie != null) {
firstName = myCookie.getValue();
session.setAttribute(SystemGlobals.getValue(ConfigKeys.SSO_FIRSTNAME_ATTRIBUTE), URLDecoder.decode(firstName, encoding));
}
myCookie = ControllerUtils.getCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_NAME_LAST));
if (myCookie != null) {
lastName = myCookie.getValue();
session.setAttribute(SystemGlobals.getValue(ConfigKeys.SSO_LASTNAME_ATTRIBUTE), URLDecoder.decode(lastName, encoding));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return username; // jforum username
}

public boolean isSessionValid(UserSession userSession, RequestContext request) {
Cookie SSOCookie = ControllerUtils.getCookie(
SystemGlobals.getValue(ConfigKeys.COOKIE_NAME_USER)); // myapp login cookie
String remoteUser = null;

if (SSOCookie != null) {
remoteUser = SSOCookie.getValue(); // jforum username
}

// user has since logged out
if (remoteUser == null
&& userSession.getUserId() != SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID)) {
return false;
// user has since logged in
} else if (remoteUser != null
&& userSession.getUserId() == SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID)) {
return false;
// user has changed user
} else if (remoteUser != null && !remoteUser.equals(userSession.getUsername())) {
return false;
}
return true; // myapp user and forum user the same
}
}

5.Modify net.jforum.ControllerUtils.java:
edit method: protected void checkSSO(UserSession userSession)

/**
* Checks for user authentication using some SSO implementation
* @param userSession UserSession
*/
protected void checkSSO(UserSession userSession)
{
try {
SSO sso = (SSO) Class.forName(SystemGlobals.getValue(ConfigKeys.SSO_IMPLEMENTATION)).newInstance();
String username = sso.authenticateUser(JForumExecutionContext.getRequest());

if (username == null || username.trim().equals("")) {
userSession.makeAnonymous();
}
else {
SSOUtils utils = new SSOUtils();

if (!utils.userExists(username)) {
SessionContext session = JForumExecutionContext.getRequest().getSessionContext();

String email = (String) session.getAttribute(SystemGlobals.getValue(ConfigKeys.SSO_EMAIL_ATTRIBUTE));
String password = (String) session.getAttribute(SystemGlobals.getValue(ConfigKeys.SSO_PASSWORD_ATTRIBUTE));
String firstName = (String) session.getAttribute(SystemGlobals.getValue(ConfigKeys.SSO_FIRSTNAME_ATTRIBUTE));
String lastName = (String) session.getAttribute(SystemGlobals.getValue(ConfigKeys.SSO_LASTNAME_ATTRIBUTE));

if (email == null) {
email = SystemGlobals.getValue(ConfigKeys.SSO_DEFAULT_EMAIL);
}

if (password == null) {
password = SystemGlobals.getValue(ConfigKeys.SSO_DEFAULT_PASSWORD);
}

if (firstName == null) {
firstName = SystemGlobals.getValue(ConfigKeys.SSO_DEFAULT_FIRSTNAME);
}

if (lastName == null) {
lastName = SystemGlobals.getValue(ConfigKeys.SSO_DEFAULT_LASTNAME);
}

utils.register(password, email, firstName, lastName);
}

this.configureUserSession(userSession, utils.getUser());
}
}
catch (Exception e) {
e.printStackTrace();
throw new ForumException("Error while executing SSO actions: " + e);
}
}

6.Modify net.jforum.sso.SSOUtils.java
add a new method: public void register(String password, String email, String firstName, String lastName)

/**
* Registers a new user.
* This method should be used together with {@link #userExists(String)}.
*
* @param password the user's password. It <em>should</em> be the real / final
* password. In other words, the data passed as password is the data that'll be
* written to the database
* @param email the user's email
* @param firstName the user's first name
* @param lasstName the user's last name
* @see #getUser()
*/
public void register(String password, String email, String firstName, String lastName)
{
if (this.exists) {
return;
}

// Is a new user for us. Register him
this.user = new User();
user.setUsername(this.username);
user.setPassword(password);
user.setEmail(email);
user.setActive(1);
user.setFirstName(firstName);
user.setLastName(lastName);

this.dao.addNew(user);
}

7.Modify net.jforum.dao.generic.GenericUserDAO.java
store firstName and lastName to database

protected void initNewUser(User user, PreparedStatement p) throws SQLException
{
p.setString(1, user.getUsername());
p.setString(2, user.getPassword());
p.setString(3, user.getEmail());
p.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
p.setString(5, user.getActivationKey());
p.setString(6, user.getFirstName());
p.setString(7, user.getLastName());
}

8.Modify WEB-INF/config/database/generic/generic_queries.sql

UserModel.addNew = INSERT INTO jforum_users (username, user_password, user_email, user_regdate, user_actkey, rank_id, first_name, last_name) VALUES (?, ?, ?, ?, ?, 0, ?, ?)

Oracle Database user have to edit WEB-INF/config/database/oracle/oracle.sql

UserModel.addNew = INSERT INTO jforum_users (user_id, username, user_password, user_email, user_regdate, user_actkey, rank_id, first_name, last_name) VALUES (jforum_users_seq.nextval, ?, ?, ?, ?, ?, 0, ?, ?)

9.Edit /sso/login.jsp on member.andowson.com

<%@ page contentType="text/html;charset=big5" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5" />
<title>JForum SSO Login</title>
</head>
<body>
<form name="loginform" method="post" action="proc_login.jsp">
<input type="hidden" name="redirect" value="<%=request.getParameter("returnUrl")%>" />
<div align="center">
Username: <input type="text" name="username" />

Password: <input type="password" name="password" />

<input type="submit" value="Login" />
</div>
</form>
</body>
</html>

10.Edit /sso/proc_login.jsp on member.andowson.com

<%@ page contentType="text/html;charset=big5" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.Properties" %>
<%@ page import="com.oreilly.servlet.ParameterParser" %>
<%
ParameterParser parser = new ParameterParser(request);
parser.setCharacterEncoding("Big5");
String username = parser.getStringParameter("username", null);
String password = parser.getStringParameter("password", null);
String redirect = parser.getStringParameter("redirect", null);

Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
String email = null;
String firstName = null;
String lastName = null;
boolean login = false;

if (username != null && password != null) {
try {
final String url = "jdbc:postgresql://127.0.0.1:5432/member";
final Properties info = new Properties();
info.setProperty("user", "member");
info.setProperty("password", "member");
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection(url, info);
sql = "select * from users where username = ? and password = ?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
if (rs.next()) {
email = rs.getString("email");
firstName = rs.getString("first_name");
lastName = rs.getString("last_name");
login = true;
}
rs.close();
rs = null;
pstmt.close();
pstmt = null;
con.close();
con = null;
} catch (SQLException se) {
out.println(se.getMessage());
} finally {
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
out.println(e.getMessage());
}
rs = null;
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
out.println(e.getMessage());
}
pstmt = null;
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
out.println(e.getMessage());
}
con = null;
}
}
}
if (login) {
Cookie cookieUsername = new Cookie("username", username);
cookieUsername.setMaxAge(-1);
cookieUsername.setPath("/");
response.addCookie(cookieUsername);

Cookie cookieEmail = new Cookie("email", java.net.URLEncoder.encode(email, "Big5"));
cookieEmail.setMaxAge(-1);
cookieEmail.setPath("/");
response.addCookie(cookieEmail);

Cookie cookieFirstName = new Cookie("firstname", java.net.URLEncoder.encode(firstName, "Big5"));
cookieFirstName.setMaxAge(-1);
cookieFirstName.setPath("/");
response.addCookie(cookieFirstName);

Cookie cookieLastName = new Cookie("lastname", java.net.URLEncoder.encode(lastName, "Big5"));
cookieLastName.setMaxAge(-1);
cookieLastName.setPath("/");
response.addCookie(cookieLastName);

if (redirect != null && redirect.trim().length() > 0 && !"null".equals(redirect)) {
response.sendRedirect(redirect);
}
} else {
out.println("Login failed!");
}
%>

 檔案名稱 proc_login.jsp [Disk] 下載
 描述 Sample Login Processing Logic
 檔案大小 4 Kbytes
 下載次數:  15 次

 檔案名稱 login.jsp [Disk] 下載
 描述 Sample Login Form
 檔案大小 719 bytes
 下載次數:  19 次

 檔案名稱 MyUserSSO.java [Disk] 下載
 描述 JForum Cookie-based SSO with extra user data registered
 檔案大小 3 Kbytes
 下載次數:  17 次


分享經驗 累積智慧
[WWW]
 
討論區首頁 » JForum中文社群 JForum Chinese Users Community
前往:   
行動版