use of com.sun.identity.authentication.AuthContext in project OpenAM by OpenRock.
the class TokenUtils method getSessionToken.
public static SSOToken getSessionToken(String orgName, String userId, String password, String module, int level) throws Exception {
AuthContext ac = null;
try {
//System.out.println("TokenUtils:orgName=" + orgName);
ac = new AuthContext(orgName);
if (module != null) {
ac.login(AuthContext.IndexType.MODULE_INSTANCE, module);
} else if (level != -1) {
ac.login(AuthContext.IndexType.LEVEL, String.valueOf(level));
} else {
//System.out.println("TokenUtils:calling login()");
ac.login();
}
//System.out.println("TokenUtils:after ac.login()");
} catch (LoginException le) {
le.printStackTrace();
return null;
}
try {
Callback[] callbacks = null;
// Get the information requested by the plug-ins
if (ac.hasMoreRequirements()) {
callbacks = ac.getRequirements();
if (callbacks != null) {
addLoginCallbackMessage(callbacks, userId, password);
ac.submitRequirements(callbacks);
if (ac.getStatus() == AuthContext.Status.SUCCESS) {
//System.out.println("Auth success");
Subject authSubject = ac.getSubject();
if (authSubject != null) {
Iterator principals = (authSubject.getPrincipals()).iterator();
Principal principal;
while (principals.hasNext()) {
principal = (Principal) principals.next();
}
}
} else if (ac.getStatus() == AuthContext.Status.FAILED) {
//System.out.println("Authentication has FAILED");
} else {
}
} else {
}
}
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println(ac.getSSOToken().getPrincipal().getName());
return ac.getSSOToken();
}
use of com.sun.identity.authentication.AuthContext in project OpenAM by OpenRock.
the class LogSample method logWriteProcessing.
private void logWriteProcessing() {
/*
* get:
* 1. subject userid (subject of the LogRecord)
* 2. subject userid's password
* 3. Log filename to log to
* 4. LogRecord's "data"
* 5. LoggedBy userid (who's doing the logging)
* 6. LoggedBy userid's password
* 7. Realm (for both subject userid and LoggedBy userid
* in this sample)
*/
String userSID = sampleUtils.getLine("Subject Userid", DEF_USERNAME);
String userPWD = sampleUtils.getLine("Subject Userid " + userSID + "'s password", DEF_USERPSWD);
String logName = sampleUtils.getLine("Log file", DEF_LOGNAME);
String message = sampleUtils.getLine("Log message", DEF_LOGMSG);
;
String loggedBySID = sampleUtils.getLine("LoggedBy Userid", DEF_LOGGEDBY);
String loggedByPWD = sampleUtils.getLine("LoggedBy Userid's password", DEF_LOGGEDBYPSWD);
String realmName = sampleUtils.getLine("Realm", DEF_REALM);
// get AuthContexts for subject userid and loggedby userid
try {
userAC = new AuthContext(realmName);
loggerAC = new AuthContext(realmName);
} catch (AuthLoginException le) {
System.err.println("LogSampleUtils: could not get AuthContext for realm " + realmName);
System.exit(2);
}
// do user and loggedby login and get the SSOToken
try {
userSSOToken = sampleUtils.realmLogin(userSID, userPWD, userAC);
loggerSSOToken = sampleUtils.realmLogin(loggedBySID, loggedByPWD, loggerAC);
} catch (SSOException ssoe) {
System.err.println("logWriteProcessing: could not get SSOToken: " + ssoe.getMessage());
System.exit(3);
} catch (AuthLoginException ale) {
System.err.println("logWriteProcessing: could not authenticate: " + ale.getMessage());
System.exit(4);
} catch (Exception e) {
System.err.println("logWriteProcessing: exception getting SSOToken: " + e.getMessage());
System.exit(5);
}
try {
LogRecord logRecord = new LogRecord(java.util.logging.Level.INFO, message, userSSOToken);
logRecord.addLogInfo("ModuleName", DEF_MODULENAME);
java.net.InetAddress ipAddr = java.net.InetAddress.getLocalHost();
logRecord.addLogInfo("IPAddr", ipAddr.getHostAddress());
Logger logger = (Logger) Logger.getLogger(logName);
logger.log(logRecord, loggerSSOToken);
System.out.println("LogSample: Logging Successful !!!");
userAC.logout();
loggerAC.logout();
} catch (AMLogException amex) {
System.err.println("LogSample: AMLogException: " + amex.getMessage());
System.err.println("LogSample: Logging Failed; " + "Is user '" + loggedBySID + "' a member of a Role or Group with log writing privileges?");
} catch (Exception ssoe) {
System.err.println("LogSample: Exception: " + ssoe.getMessage());
System.err.println("LogSample: Logging Failed !!!");
}
}
use of com.sun.identity.authentication.AuthContext in project OpenAM by OpenRock.
the class SampleBase method authenticate.
protected AuthContext authenticate(String orgname, String username, String password, PrintWriter out) throws Exception {
// Authenticate the user and obtain SSO Token
AuthContext lc = new AuthContext(orgname);
lc.login();
while (lc.hasMoreRequirements()) {
Callback[] callbacks = lc.getRequirements();
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
NameCallback nc = (NameCallback) callbacks[i];
nc.setName(username);
} else if (callbacks[i] instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) callbacks[i];
pc.setPassword(password.toCharArray());
} else {
out.println("Unknow Callback: " + callbacks[i]);
out.println("</body></html>");
return null;
}
}
lc.submitRequirements(callbacks);
}
if (lc.getStatus() != AuthContext.Status.SUCCESS) {
out.println("Invalid credentials");
out.println("</body></html>");
return null;
}
return lc;
}
use of com.sun.identity.authentication.AuthContext in project OpenAM by OpenRock.
the class ServiceConfigServlet method doGet.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get query parameters
String orgname = request.getParameter("orgname");
if (orgname == null || orgname.length() == 0) {
orgname = "/";
}
String username = request.getParameter("username");
String password = request.getParameter("password");
String servicename = request.getParameter("service");
String method = request.getParameter("method");
if (method == null) {
method = "globalSchema";
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(SampleConstants.HTML_HEADER);
if (username == null || password == null || servicename == null) {
out.println("Value for user name, password and service name are required.");
out.println("</body></html>");
return;
}
out.println("<h3>ServiceName:</h3> " + servicename);
out.println("<br><h3>Username:</h3> " + username);
try {
AuthContext lc = authenticate(orgname, username, password, out);
if (lc != null) {
if (lc.getStatus() != AuthContext.Status.SUCCESS) {
out.println("Invalid credentials");
out.println("</body></html>");
} else {
printInfo(lc, servicename, method, out);
}
}
} catch (Exception e) {
e.printStackTrace(out);
out.println("</body></html>");
}
}
use of com.sun.identity.authentication.AuthContext in project OpenAM by OpenRock.
the class FMSessionProvider method createSession.
/**
* Meaningful only for SP side, the implementation of this method
* will create a local session for the local user identified by
* the information in the map. The underline mechanism of the
* session creation and management is application specific.
* For example, it could be cookie setting or url rewriting, which
* is expected to be done by the implementation of this method.
* Note that only the first input parameter is mandatory. Normally,
* at least one of the last two parameters should not be null
*
* @param info a Map with keys and values being of type String; The
* keys will include "principalName" (returned from
* SPAccountMapper), "realm", "authLevel", and may
* include "resourceOffering" and/or "idpEntityID";
* The implementation of this method could choose to set
* some of the information contained in the map into the
* newly created Session by calling setProperty(), later
* the target application may consume the information.
* @param request the HttpServletRequest the user made to initiate
* the SSO.
* @param response the HttpServletResponse that will be sent to the
* user (for example it could be used to set a cookie).
* @param targetApplication the original resource that was requested
* as the target of the SSO by the end user;
* If needed, this String could be modified,
* e.g., by appending query string(s) or by
* url rewriting, hence this is an in/out
* parameter.
* @return the newly created local user session.
* @throws SessionException if an error occurred during session
* creation.
*/
public Object createSession(// in
Map info, // in
HttpServletRequest request, // in/out
HttpServletResponse response, // in/out
StringBuffer targetApplication) throws SessionException {
String realm = (String) info.get(REALM);
if (realm == null || realm.length() == 0) {
throw new SessionException(bundle.getString("nullRealm"));
}
String principalName = (String) info.get(PRINCIPAL_NAME);
if (principalName == null || principalName.length() == 0) {
throw new SessionException(bundle.getString("nullPrincipal"));
}
String authLevel = (String) info.get(AUTH_LEVEL);
Object oldSession = null;
if (request != null) {
try {
oldSession = getSession(request);
String oldPrincipal = getPrincipalName(oldSession);
oldPrincipal = oldPrincipal.toLowerCase();
if ((!oldPrincipal.equals(principalName.toLowerCase())) && (!oldPrincipal.startsWith("id=" + principalName.toLowerCase() + ","))) {
invalidateSession(oldSession, request, response);
oldSession = null;
}
} catch (SessionException se) {
oldSession = null;
}
}
// Call auth module "Federation"
AuthContext ac = null;
try {
if (oldSession != null) {
ac = new AuthContext((SSOToken) oldSession, true);
} else {
ac = new AuthContext(realm);
}
ac.login(AuthContext.IndexType.MODULE_INSTANCE, "Federation", null, null, request, response);
} catch (AuthLoginException ale) {
throw new SessionException(ale);
}
Callback[] callbacks = null;
while (ac.hasMoreRequirements()) {
callbacks = ac.getRequirements();
if (callbacks == null || callbacks.length == 0) {
continue;
}
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
NameCallback nc = (NameCallback) callbacks[i];
if (nc.getPrompt().equals(PRINCIPAL_NAME)) {
nc.setName(principalName);
} else if (nc.getPrompt().equals(RANDOM_SECRET)) {
String randomString = generateSecret();
while (secretSet.contains(randomString)) {
randomString = generateSecret();
}
secretSet.add(randomString);
nc.setName(randomString);
} else if (nc.getPrompt().equals(AUTH_LEVEL)) {
nc.setName(authLevel);
}
}
}
break;
}
ac.submitRequirements(callbacks);
SSOToken ssoToken = null;
if (ac.getStatus() == AuthContext.Status.SUCCESS) {
try {
ssoToken = ac.getSSOToken();
} catch (Exception e) {
throw new SessionException(e.getMessage());
}
} else if (ac.getStatus() == AuthContext.Status.FAILED) {
// TODO: test again when auth changes are done so the error code
// is set and passed over
int failureCode = SessionException.AUTH_ERROR_NOT_DEFINED;
AuthLoginException ale = ac.getLoginException();
String authError = null;
if (ale != null) {
authError = ale.getErrorCode();
}
if (authError == null) {
failureCode = SessionException.AUTH_ERROR_NOT_DEFINED;
} else if (authError.equals(AMAuthErrorCode.AUTH_USER_INACTIVE)) {
failureCode = SessionException.AUTH_USER_INACTIVE;
} else if (authError.equals(AMAuthErrorCode.AUTH_USER_LOCKED)) {
failureCode = SessionException.AUTH_USER_LOCKED;
} else if (authError.equals(AMAuthErrorCode.AUTH_ACCOUNT_EXPIRED)) {
failureCode = SessionException.AUTH_ACCOUNT_EXPIRED;
}
SessionException se = null;
if (ale != null) {
se = new SessionException(ale);
} else {
se = new SessionException(bundle.getString("loginFailed"));
}
se.setErrCode(failureCode);
throw se;
} else {
throw new SessionException(bundle.getString("loginFailed"));
}
if (response != null) {
ServiceSchemaManager scm = null;
try {
scm = new ServiceSchemaManager("iPlanetAMPlatformService", ssoToken);
} catch (Exception e) {
throw new SessionException(e);
}
ServiceSchema platformSchema = null;
try {
platformSchema = scm.getGlobalSchema();
} catch (SMSException se) {
throw new SessionException(se);
}
setLoadBalancerCookie(request, response);
Set cookieDomains = (Set) platformSchema.getAttributeDefaults().get("iplanet-am-platform-cookie-domains");
String value = ssoToken.getTokenID().toString();
if (cookieDomains.size() == 0) {
Cookie cookie = CookieUtils.newCookie(cookieName, value, "/");
CookieUtils.addCookieToResponse(response, cookie);
} else {
Iterator it = cookieDomains.iterator();
Cookie cookie = null;
String cookieDomain = null;
while (it.hasNext()) {
cookieDomain = (String) it.next();
if (debug.messageEnabled()) {
debug.message("cookieName=" + cookieName);
debug.message("value=" + value);
debug.message("cookieDomain=" + cookieDomain);
}
cookie = CookieUtils.newCookie(cookieName, value, "/", cookieDomain);
CookieUtils.addCookieToResponse(response, cookie);
}
}
if (urlRewriteEnabled && targetApplication != null) {
int n = targetApplication.length();
if (n > 0) {
String rewrittenURL = rewriteURL(ssoToken, targetApplication.toString());
targetApplication.delete(0, n);
targetApplication.append(rewrittenURL);
}
}
}
// set all properties in the info map to sso token
try {
Iterator it = info.keySet().iterator();
while (it.hasNext()) {
String keyName = (String) it.next();
if (keyName.equals(AUTH_LEVEL)) {
continue;
}
String keyVal = (String) info.get(keyName);
ssoToken.setProperty(keyName, StringUtils.getEscapedValue(keyVal));
}
} catch (SSOException se) {
throw new SessionException(se);
}
return ssoToken;
}
Aggregations