• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Not able to retrieve cookie information

 
Ranch Hand
Posts: 17424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I am trying to use the SSO using cookies.

But i am not able to retrieve the information in cookie in Jforum application.


Can somebody please help me ?

Thanks
[originally posted on jforum.net by jforumUser]
 
Migrated From Jforum.net
Ranch Hand
Posts: 17424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Just elaborating on the issue.

I am trying to integrate Jforum with an application. Only registered users can access the forum.

I am using SSO with the help of cookies. I am facing problem while retrieving the cookie.

Following is the code:

SystemGlobals.properties
:

authentication.type=sso

login.authenticator = net.jforum.sso.DefaultLoginAuthenticator

auto.login.enabled = true

sso.implementation=net.jforum.sso.MyUserSSO

sso.password.attribute = password

sso.email.attribute = email

sso.default.email = sso@user

sso.default.password = sso

sso.redirect=http://localhost/JStre/Login

sso.cookie.path=/

ldap.security.protocol =

ldap.authentication =

ldap.factory = com.sun.jndi.ldap.LdapCtxFactory

ldap.login.prefix = uid=

ldap.login.suffix = ou=Users,dc=department,dc=company,dc=com

ldap.server.url = ldap://localhost

ldap.field.email = mail

ldap.lookup.prefix =
ldap.lookup.suffix =

anonymous.userId = 1
defaultUserGroup = 1

template.dir = default

servlet.extension = .page

cookie.name.data = myCookie
cookie.name.user = jforumUserInfo
cookie.name.autologin = jforumAutoLogin
cookie.name.userHash = jforumUserHash


My application's login action has following entry :

Cookie cookie = new Cookie("myCookie", cookieInfo);
cookie.setMaxAge(-1); // session cookie, or set to positive number.
response.addCookie(cookie);


MyUserSSO.java:


package net.jforum.sso;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.StringTokenizer;

import javax.servlet.http.Cookie;

import net.jforum.ControllerUtils;
import net.jforum.JForumExecutionContext;
import net.jforum.context.RequestContext;
import net.jforum.context.SessionContext;
import net.jforum.dao.DataAccessDriver;
import net.jforum.dao.UserDAO;
import net.jforum.entities.User;
import net.jforum.entities.UserSession;
import net.jforum.repository.SecurityRepository;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.log4j.Logger;

public class MyUserSSO implements SSO { // you must implement met.jforum.sso.SSO

static final Logger logger = Logger.getLogger(MyUserSSO.class.getName()); // init logging

static final String md5Salt = "someWeirdStringSharedByTheApps";
static final int JFORUM_NORMAL_GROUP_ID = 1;
static final int JFORUM_ADMIN_GROUP_ID = 2;
static final int JFORUM_MODERATOR_GROUP_ID = 3;
/**
*
*
* Where:

* userId = Remote apps's authenticated app.

* e-mail = E-mail address of remote user's app

* group_info = Group info.
*
*/
public String authenticateUser(RequestContext request) { // required method
Cookie myCookie = ControllerUtils.getCookie("myCookie"); // my app login cookie

if (myCookie == null) { // No Cookie, so just return a null.
return null;
}

String userId = null;
String email = null;
String group_info = "general";
try {
userId = myCookie.getValue();
/* email = st.nextToken();
group_info = st.nextToken();
md5String = st.nextToken();*/
} catch ( Exception e ) {
logger.warn("Found SSO Cookie, but could not parse it! "+
"userId='"+userId+"' md5='"+"md5String"+"'",e);
return null;
}

/* //Validate the cookie's MD5 Hash
try {
if (! makeMD5Token(userId, email, group_info).equals(md5String)) {
logger.warn("Found SSO cookie with invalid MD5 security hash!");
return null;
}
} catch ( Exception e ) {
logger.warn("Error validating md5String for cookie: '" +
myCookie.getValue());
return null;
}*/

SessionContext session = request.getSessionContext();

String lastSSOUser = (String) session.getAttribute("MY_SSO_USER");

// If lastSSOUser is set and matches, then it's valid so just
// return the name and save looking up the user, etc.
if ( lastSSOUser != null && lastSSOUser.equals(userId)) {
return lastSSOUser;
}

// Create the jForum user entry if needed.
SSOUtils utils = new SSOUtils();

String password = null; // Could set a password here if desired.
if (!utils.userExists(userId)) {

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

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

utils.register(password, email);
}
User user = utils.getUser();

session.setAttribute("MY_SSO_USER", userId);

// Make sure user group info is current with each "login".

UserDAO um = DataAccessDriver.getInstance().newUserDAO();

int[] disallowedGroups = null;
int[] allowedGroups = null;

if ( group_info.equals("admin")) {
allowedGroups = new int[3];
allowedGroups[0] = JFORUM_NORMAL_GROUP_ID;
allowedGroups[1] = JFORUM_MODERATOR_GROUP_ID;
allowedGroups[2] = JFORUM_ADMIN_GROUP_ID;
} else if ( group_info.equals("moderator" )){
disallowedGroups = new int[1];
disallowedGroups[0] = JFORUM_ADMIN_GROUP_ID;
allowedGroups = new int[2];
allowedGroups[0] = JFORUM_NORMAL_GROUP_ID;
allowedGroups[1] = JFORUM_MODERATOR_GROUP_ID;
} else {
disallowedGroups = new int[2];
disallowedGroups[0] = JFORUM_ADMIN_GROUP_ID;
disallowedGroups[1] = JFORUM_MODERATOR_GROUP_ID;
allowedGroups = new int[1];
allowedGroups[0] = JFORUM_NORMAL_GROUP_ID;
}
if ( disallowedGroups != null ) {
um.removeFromGroup(user.getId(), disallowedGroups);
}
um.addToGroup(user.getId(), allowedGroups);
SecurityRepository.remove(user.getId());

// User by isSessionValid.
Cookie cookie = new Cookie("JforumSSO", userId);
cookie.setMaxAge(myCookie.getMaxAge());
cookie.setPath("/");
JForumExecutionContext.getResponse().addCookie(cookie);

return userId;
}

public boolean isSessionValid(UserSession userSession, RequestContext request) {
String remoteUser = null;
Cookie SSOCookie = ControllerUtils.getCookie("JforumSSO");
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
}
/**
* Makes the MD5 token used for authentication in cookies.
*
* @param userName The user id used for encryption.
* @param email The user's email (or "" if none).
* @return The hex string representation of the MD5 digested string.
* @exception NoSuchAlgorithException If for some reason, MD5 is not available?
*/
private String makeMD5Token (String userName, String email,
String groupInfo )
throws NoSuchAlgorithmException {
MessageDigest md;
byte[] sig;
String plainText;
StringBuffer encryptedText = new StringBuffer();

plainText = md5Salt + "/" + userName + "/"+ email + "/"+groupInfo;
md = MessageDigest.getInstance("MD5");

sig = md.digest(plainText.getBytes());

for ( int i = 0; i < sig.length; i++ ) {
encryptedText.append(Integer.toString(( sig[i] & 0xff ) + 0x100, 16 ).substring(1));
}
return encryptedText.toString();
}
}




[originally posted on jforum.net by jforumUser]
 
Migrated From Jforum.net
Ranch Hand
Posts: 17424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First, I think that is an older version of an update sample CookieSSO class I've been expanding on for a while. You might want to look at the latest version in this post:

http://www.jforum.net/posts/list/15/4414.page#18206

That said, a quick suggestion would be to call the setPath() and setDomain methods in your main application to make sure that the cookie will be passed to jForum. E.g., if your application and jforum are on the same server, set the path to "/" so that it's shared across all URL on that server. If they are on separate hosts in the same domain, you can use the setDomain to tell the browser to pass it to other machines (but the Browser may need to be configured to allow such cookies...)

Also, make sure that your jForum config file settings are not "re-writing" the host name in the URLs.. e.g., you start with myapp.my.biz in your application, but jforum is configured to use localhost or something else. In this case the cookie will not be passed to jForum.

Finally, to help track down what's happening, you can make use of the log4j "logger" that's defined for this class. E.g., you can put in "debug" statements in the SSO code to tell you what's going on. E.g. add stuff like:

logger.info("Did not find cookie...");

This should put information into the tomcat or jforum log files, depending on how you've got your log4j config set up.

Also there are a lot of tools that will let you examine the cookies (and other info) being passed on your request. Like the Firefox Web Developer add-in and I think FireFly does this too.
[originally posted on jforum.net by monroe]
 
Migrated From Jforum.net
Ranch Hand
Posts: 17424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Monroe,

Thanks for reply.
Setting the path of cookie to "/" worked for me.

Thanks,
[originally posted on jforum.net by jforumUser]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic