Author: ivol37 at gmail.com
Date: Fri Dec 10 14:13:42 2010
New Revision: 487
Log:
[AMDATU-202] Replaced micky mouse authorize.jsp with a version that actually
verifies against an Amdatu account. Also refactored the integration test to use
this new authorization step. Doing this some minor bugs in the BasicHttpSession
and LoginServiceImpl came to light which have been fixed with this commit.
Finally removed some unused oAuth related code.
Removed:
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthServlet.java
trunk/amdatu-opensocial/dashboard/src/main/resources/jsp/authorize.jsp
Modified:
trunk/amdatu-authentication/oauth-api/src/main/java/org/amdatu/authentication/oauth/api/OAuthServiceProvider.java
trunk/amdatu-authentication/oauth-client/src/main/java/org/amdatu/authentication/oauth/client/OAuthResourceOwnerClient.java
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/OAuthServerConfig.java
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/osgi/Activator.java
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthAuthorizeTokenServletImpl.java
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthServiceProviderImpl.java
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthTokenProviderImpl.java
trunk/amdatu-authentication/oauth-server/src/main/resources/jsp/authorize.jsp
trunk/amdatu-authorization/login-service/src/main/java/org/amdatu/authorization/login/service/service/LoginServiceImpl.java
trunk/amdatu-core/config-filebased/src/main/resources/conf/org.amdatu.authentication.oauth.server.cfg
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/DummyInterface.java
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthGadgetsRegistrationServiceImpl.java
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthProtectedResource.java
trunk/amdatu-web/httpcontext/src/main/java/org/amdatu/web/httpcontext/BasicHttpSession.java
trunk/integration-tests/pom.xml
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/ConfigProvider.java
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/IntegrationTestBase.java
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/OAuthTestBase.java
trunk/integration-tests/src/test/java/org/amdatu/test/integration/tests/OAuthThreeLeggedTest.java
trunk/integration-tests/src/test/java/org/amdatu/test/integration/tests/OAuthTwoLeggedTest.java
Modified:
trunk/amdatu-authentication/oauth-api/src/main/java/org/amdatu/authentication/oauth/api/OAuthServiceProvider.java
==============================================================================
---
trunk/amdatu-authentication/oauth-api/src/main/java/org/amdatu/authentication/oauth/api/OAuthServiceProvider.java
(original)
+++
trunk/amdatu-authentication/oauth-api/src/main/java/org/amdatu/authentication/oauth/api/OAuthServiceProvider.java
Fri Dec 10 14:13:42 2010
@@ -46,4 +46,13 @@
* @return The absolute URL of the access token endpoint.
*/
String getAccessTokenURL();
+
+ /**
+ * Returns the URL to the login and allow access page. This page is used
to let the end-user login and
+ * specifically grant or deny access to the service consumer requesting
access to its protected resources.
+ * After the user has logged in and access has been granted, the token to
authorize should be posted to
+ * the authorize token URL.
+ * @return The login/allow access page URL
+ */
+ String getAuthorizeURL();
}
Modified:
trunk/amdatu-authentication/oauth-client/src/main/java/org/amdatu/authentication/oauth/client/OAuthResourceOwnerClient.java
==============================================================================
---
trunk/amdatu-authentication/oauth-client/src/main/java/org/amdatu/authentication/oauth/client/OAuthResourceOwnerClient.java
(original)
+++
trunk/amdatu-authentication/oauth-client/src/main/java/org/amdatu/authentication/oauth/client/OAuthResourceOwnerClient.java
Fri Dec 10 14:13:42 2010
@@ -58,21 +58,22 @@
}
/**
- * Authorizes a request token with the specified userId. Note that using
this client no user
- * interaction is required to be able to authorize a token.
+ * Authorizes a request token for a user that is currently logged in. Note
that it is required that this
+ * method is invoked after the user has already logged in in Amdatu, using
the REST login service for example.
+ * This method only grants access to the specified service consumer on
behalf of the user currently logged in.
*
* @param accessor The OAuth accessor which contains the request token to
be authorized. The
* accessor is returned when the request token is received using
the service consumer client API.
- * @param userId The id of the user to authorize the token with. The
userid will become part of
- * the access token such that the service provider can retrieve the
userid and perform
- * authorization checks.
+ * @param requestHeaders Map of request headers which should be send along
with the request. This may be necessary
+ * for example to pass a site authentication cookie (i.e.
jsessionid).
* @return The callback URL of the service consumer.
* @throws IOException In case a I/O exception occurred
* @throws URISyntaxException In case some URL could not be parsed
* @throws OAuthException If the received request token is invalid
* @return The callback url, if the service consumer provided it
*/
- public String authorizeToken(OAuthAccessor accessor, String userId) throws
IOException, URISyntaxException,
+ public String authorizeToken(OAuthAccessor accessor, Map<String, String>
requestHeaders) throws IOException,
+ URISyntaxException,
OAuthException {
Map<String, String> paramProps = new HashMap<String, String>();
paramProps.put("oauth_token", accessor.requestToken);
@@ -92,23 +93,38 @@
// Now build the post request
HttpClient httpClient = new HttpClient();
NameValuePair[] data = {
- new NameValuePair("userId", userId),
new NameValuePair("oauth_token", token),
new NameValuePair("oauth_callback", callback)
};
- PostMethod postMethod = new
PostMethod(getProvider().getAuthorizeTokenURL());
- postMethod.setRequestBody(data);
- int status = httpClient.executeMethod(postMethod);
- if (status == HttpStatus.SC_OK) {
- // Status 200 means authorize token went OK, but service consumer
did not specify a callback URL
- return null;
- }
- else if (status == HttpStatus.SC_MOVED_TEMPORARILY) {
- // Status 302 means that we are being redirected to the callback
url provided by the service consumer
- return postMethod.getResponseHeader("Location").getValue();
+ PostMethod postMethod = null;
+ try {
+ postMethod = new PostMethod(getProvider().getAuthorizeTokenURL());
+ postMethod.setRequestBody(data);
+ if (requestHeaders != null) {
+ for (String headerName : requestHeaders.keySet()) {
+ String headerValue = requestHeaders.get(headerName);
+ postMethod.setRequestHeader(headerName, headerValue);
+ }
+ }
+
+ int status = httpClient.executeMethod(postMethod);
+ if (status == HttpStatus.SC_OK) {
+ // Status 200 means authorize token went OK, but service
consumer did not specify a callback URL
+ return null;
+ }
+ else if (status == HttpStatus.SC_MOVED_TEMPORARILY) {
+ // Status 302 means that we are being redirected to the
callback url provided by the service consumer
+ return postMethod.getResponseHeader("Location").getValue();
+ }
+ else {
+ throw new OAuthException("Authorize token form returned " +
status);
+ }
}
- else {
- throw new OAuthException("Authorize token form returned " +
status);
+ finally {
+ // Release the connection.
+ if (postMethod != null) {
+ postMethod.releaseConnection();
+ }
}
}
}
Modified:
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/OAuthServerConfig.java
==============================================================================
---
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/OAuthServerConfig.java
(original)
+++
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/OAuthServerConfig.java
Fri Dec 10 14:13:42 2010
@@ -37,6 +37,15 @@
*/
public final static String PORTNR = "portnr";
+ /**
+ * The URL that hosts the login/grant access functionality. By default the
Amdatu oAuth server provides
+ * a simple authorize.jsp that asks the visitor for an amdatu login and
password and then asks if the
+ * user wants to grant access or not. This configuration property can be
changed to point to any
+ * other login/grant access page. Note however that as a result of it, the
user must be logged in with
+ * an Amdatu account and the request token must be submitted to the
authorize token servlet.
+ */
+ public final static String AUTHORIZE_URL = "authorizeurl";
+
// Mark the constructor private since this class intends to provide only
static fields.
private OAuthServerConfig() {
}
Modified:
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/osgi/Activator.java
==============================================================================
---
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/osgi/Activator.java
(original)
+++
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/osgi/Activator.java
Fri Dec 10 14:13:42 2010
@@ -73,6 +73,7 @@
createComponent()
.setInterface(new String[]{OAuthServiceProvider.class.getName(),
ManagedService.class.getName()}, null)
.setImplementation(OAuthServiceProviderImpl.class)
+
.add(createServiceDependency().setService(LogService.class).setRequired(true))
.add(createConfigurationDependency().setPid(OAuthServerConfig.PID)));
// Create and register the oAuth service consumer registry REST service
@@ -97,6 +98,7 @@
.setInterface(new String[]{servletInterface.getName(),
Servlet.class.getName()}, servletProperties)
.setImplementation(servletClass)
.add(createServiceDependency().setService(OAuthTokenProvider.class).setRequired(true))
+
.add(createServiceDependency().setService(OAuthServiceProvider.class).setRequired(true))
.add(createServiceDependency().setService(LogService.class).setRequired(true));
}
Modified:
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthAuthorizeTokenServletImpl.java
==============================================================================
---
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthAuthorizeTokenServletImpl.java
(original)
+++
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthAuthorizeTokenServletImpl.java
Fri Dec 10 14:13:42 2010
@@ -29,11 +29,15 @@
import net.oauth.OAuth;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthMessage;
+import net.oauth.OAuthProblemException;
import net.oauth.server.OAuthServlet;
+import org.amdatu.authentication.oauth.api.OAuthServiceProvider;
import org.amdatu.authentication.oauth.server.OAuthAuthorizeTokenServlet;
import org.amdatu.authentication.oauth.server.OAuthTokenProvider;
+import org.amdatu.web.httpcontext.BasicHttpSession;
import org.osgi.service.log.LogService;
+import org.osgi.service.useradmin.Authorization;
public class OAuthAuthorizeTokenServletImpl extends HttpServlet implements
OAuthAuthorizeTokenServlet {
// The serial version UID of this servlet
@@ -42,7 +46,8 @@
// Service dependencies, injected by the Felix dependency manager
private volatile LogService m_logService;
private volatile OAuthTokenProvider m_tokenProvider;
-
+ private volatile OAuthServiceProvider m_serviceProvider;
+
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
@@ -71,9 +76,12 @@
try {
OAuthMessage requestMessage = OAuthServlet.getMessage(request,
null);
OAuthAccessor accessor =
m_tokenProvider.getAccessor(requestMessage);
- String userId = request.getParameter("userId");
+ String userId = getUserId(request);
if (userId == null) {
- sendToAuthorizePage(request, response, accessor);
+ // If there is no userid available now, we throw a permission
denied as it won't happen in a normal situation!
+ // Maybe it's a hack attempt.
+ OAuthProblemException problem = new
OAuthProblemException("permission_denied");
+ throw problem;
}
// set userId in accessor and mark it as authorized
m_tokenProvider.markAsAuthorized(accessor, userId);
@@ -90,26 +98,22 @@
if (callback == null || callback.length() <= 0) {
callback = "none";
}
- String consumer_description = (String)
accessor.consumer.getProperty("description");
+ String consumer_description = (String)
accessor.consumer.getProperty("name");
request.setAttribute("CONS_DESC", consumer_description);
request.setAttribute("CALLBACK", callback);
request.setAttribute("TOKEN", accessor.requestToken);
- String authorizeJsp = OAuthResourceProviderImpl.RESOURCE_ID +
"/jsp/authorize.jsp";
- m_logService.log(LogService.LOG_DEBUG, "Forwarding authorize token
request to " + authorizeJsp
+ m_logService.log(LogService.LOG_DEBUG, "Forwarding authorize token
request to " + m_serviceProvider.getAuthorizeURL()
+ ", token=" + accessor.requestToken + ", callback=" + callback);
// Create a request wrapper returning the path of the JSP servlet
instead of this servlet
HttpServletRequestWrapper wrapper = new
HttpServletRequestWrapper(request) {
public String getPathInfo() {
- // TODO: This JSP is currently a Micky Mouse example. By
simply posting a form holding
- // the userid, a request token can be authorized for that user
id. This needs to be
- // connected to the Amdatu login service, or even to a
pluggable login service.
- return "/" + OAuthResourceProviderImpl.RESOURCE_ID +
"/jsp/authorize.jsp";
+ return m_serviceProvider.getAuthorizeURL();
}
};
// Dispatch the request to the authorize JSP
- request.getRequestDispatcher("/" + authorizeJsp).forward(wrapper,
response);
+
request.getRequestDispatcher(m_serviceProvider.getAuthorizeURL()).forward(wrapper,
response);
}
private void returnToConsumer(HttpServletRequest request,
@@ -147,4 +151,15 @@
response.setHeader("Location", callback);
}
}
+
+ private String getUserId(HttpServletRequest request) {
+ BasicHttpSession session = BasicHttpSession.getSession(request);
+ if (session != null) {
+ Authorization auth = (Authorization)
session.getValue("authorization");
+ if (auth != null) {
+ return auth.getName();
+ }
+ }
+ return null;
+ }
}
Modified:
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthServiceProviderImpl.java
==============================================================================
---
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthServiceProviderImpl.java
(original)
+++
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthServiceProviderImpl.java
Fri Dec 10 14:13:42 2010
@@ -16,17 +16,23 @@
*/
package org.amdatu.authentication.oauth.server.service;
+import static
org.amdatu.authentication.oauth.server.OAuthServerConfig.AUTHORIZE_URL;
+import static
org.amdatu.authentication.oauth.server.OAuthServerConfig.HOSTNAME;
+import static org.amdatu.authentication.oauth.server.OAuthServerConfig.PORTNR;
+
import java.util.Dictionary;
import org.amdatu.authentication.oauth.api.OAuthServiceProvider;
import org.amdatu.authentication.oauth.server.OAuthAccessTokenServlet;
import org.amdatu.authentication.oauth.server.OAuthAuthorizeTokenServlet;
-import static org.amdatu.authentication.oauth.server.OAuthServerConfig.*;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
+import org.osgi.service.log.LogService;
public class OAuthServiceProviderImpl implements OAuthServiceProvider,
ManagedService {
- private String m_hostName, m_portNr;
+ private volatile LogService m_logService;
+
+ private String m_hostName, m_portNr, m_authorizeUrl;
public String getRequestTokenURL() {
if (m_hostName != null && m_portNr != null) {
@@ -55,12 +61,22 @@
}
}
+ public String getAuthorizeURL() {
+ return m_authorizeUrl;
+ }
+
+ public void start() {
+ m_logService.log(LogService.LOG_DEBUG, "oAuth serviec provider started
with config: hostname=" + m_hostName
+ + ", portnr=" + m_portNr + ", authorizeurl=" + m_authorizeUrl);
+ }
+
@SuppressWarnings("unchecked")
public void updated(Dictionary dictionary) throws ConfigurationException {
if (dictionary != null) {
checkAvailability(dictionary, new String[] { HOSTNAME, PORTNR });
m_hostName = (String) dictionary.get(HOSTNAME);
m_portNr = (String) dictionary.get(PORTNR);
+ m_authorizeUrl = (String) dictionary.get(AUTHORIZE_URL);
}
}
Modified:
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthTokenProviderImpl.java
==============================================================================
---
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthTokenProviderImpl.java
(original)
+++
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthTokenProviderImpl.java
Fri Dec 10 14:13:42 2010
@@ -196,6 +196,7 @@
}
private OAuthConsumer copy(OAuthServiceConsumer serviceConsumer) {
+ String name = serviceConsumer.getName();
String callbackUrl = serviceConsumer.getCallbackUrl();
String key = serviceConsumer.getConsumerKey();
String secret = serviceConsumer.getConsumerSecret();
@@ -203,6 +204,8 @@
String authorize = m_serviceProvider.getAuthorizeTokenURL();
String access = m_serviceProvider.getAccessTokenURL();
net.oauth.OAuthServiceProvider provider = new
net.oauth.OAuthServiceProvider(request, authorize, access);
- return new OAuthConsumer(callbackUrl, key, secret, provider);
+ OAuthConsumer consumer = new OAuthConsumer(callbackUrl, key, secret,
provider);
+ consumer.setProperty("name", name);
+ return consumer;
}
}
Modified:
trunk/amdatu-authentication/oauth-server/src/main/resources/jsp/authorize.jsp
==============================================================================
---
trunk/amdatu-authentication/oauth-server/src/main/resources/jsp/authorize.jsp
(original)
+++
trunk/amdatu-authentication/oauth-server/src/main/resources/jsp/authorize.jsp
Fri Dec 10 14:13:42 2010
@@ -1,34 +1,193 @@
-<%@page contentType="text/html"%>
-<%@page pageEncoding="UTF-8"%>
+<%@ page language="java" session="false" buffer="none" %>
+<%@ page pageEncoding="UTF-8"%>
+<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
+
+<c:set var="baseUrl"
value="http://${pageContext.request.serverName}:${pageContext.request.serverPort}"/>
+<c:set var="loginUrl"
value="${baseUrl}/rest/services/authorization/authorization/login"/>
+<c:set var="logoutUrl"
value="${baseUrl}/rest/services/authorization/authorization/logout"/>
+<c:set var="statusUrl"
value="${baseUrl}/rest/services/authorization/authorization/status"/>
+
<%
- String appDesc = (String)request.getAttribute("CONS_DESC");
- String token = (String)request.getAttribute("TOKEN");
- String callback = (String)request.getAttribute("CALLBACK");
- if(callback == null)
- callback = "";
-
+ String appDesc = (String)request.getAttribute("CONS_DESC");
+ String token = (String)request.getAttribute("TOKEN");
+ String callback = (String)request.getAttribute("CALLBACK");
+ if(callback == null) {
+ callback = "";
+ }
%>
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Your Friendly OAuth Provider</title>
- </head>
- <body>
- <jsp:include page="banner.jsp"/>
-
- <h3>"<%=appDesc%>" is trying to access your information.</h3>
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+ <title>Amdatu OAuth Provider</title>
+ <script type="text/javascript"
src="/dashboard/static/js/lib/jquery-1.4.2.min.js"></script>
+ </head>
+
+ <body>
+ <h3>Access Request</h3>
+ <hr>
+ <p>
+ <b><%=appDesc%></b> is requesting access to your amdatu.org account.
+ Do you want to allow this application to access your account information?
+ </p>
+ <p>Before access can be granted you must login with your amdatu.org
account.</p>
+ <hr>
+
+ <div id="login" style="display:none;visibility:hidden">
+ <p>
+ <table width="95%">
+ <tr>
+ <td>Username</td><td><input type="edit" id="username" value=""
onKeyPress="return submitenter(this, event)"/></td>
+ </tr>
+ <tr>
+ <td>Password</td><td><input type="password" id="password" value=""
onKeyPress="return submitenter(this, event)"/></td>
+ </tr>
+ <tr>
+ <td><input type="submit" value="Login"
onclick="javascript:login()" /></td><td/>
+ </tr>
+ <tr><td colspan="2"><font color="red"><div
id="result"></div></font></td></tr>
+ </table>
+ </p>
+ </div>
- Enter the userId you want to be known as:
- <form name="authZForm" action="/oauth-server/authorizetoken" method="POST">
- <input type="text" name="userId" value="" size="20" /><br>
+ <div id="grantaccess" style="display:none;visibility:hidden">
+ <div id="welcome_username"></div><br/>
+ Do you want to allow access to <%=appDesc%>?<br/><br/>
+
+ <form name="authorizeForm" action="/oauth-server/authorizetoken"
method="POST">
<input type="hidden" name="oauth_token" value="<%= token %>"/>
<input type="hidden" name="oauth_callback" value="<%= callback %>"/>
- <input type="submit" name="Authorize" value="Authorize"/>
- </form>
+ <input type="button" id="deny" onclick="javascript:denyAccess()"
value="Deny access"/>
+ <input type="submit" name="Authorize" value="Grant access"/>
+ </form>
+ </div>
- </body>
+ <div id="accessdenied" style="display:none;visibility:hidden">
+ <p>Access to <%=appDesc%> is denied.</p>
+ </div>
+ </body>
</html>
+
+<script type="text/javascript">
+ function showLogin() {
+ document.getElementById("login").style.visibility = "";
+ document.getElementById("login").style.display = "";
+ document.getElementById("grantaccess").style.visibility = "hidden";
+ document.getElementById("grantaccess").style.display = "none";
+ document.getElementById("accessdenied").style.visibility = "hidden";
+ document.getElementById("accessdenied").style.display = "none";
+ }
+
+ function showGrantAccess() {
+ document.getElementById("login").style.visibility = "hidden";
+ document.getElementById("login").style.display = "none";
+ document.getElementById("grantaccess").style.visibility = "";
+ document.getElementById("grantaccess").style.display = "";
+ document.getElementById("accessdenied").style.visibility = "hidden";
+ document.getElementById("accessdenied").style.display = "none";
+ }
+
+ function showAccessDenied() {
+ document.getElementById("login").style.visibility = "hidden";
+ document.getElementById("login").style.display = "none";
+ document.getElementById("grantaccess").style.visibility = "hidden";
+ document.getElementById("grantaccess").style.display = "none";
+ document.getElementById("accessdenied").style.visibility = "";
+ document.getElementById("accessdenied").style.display = "";
+ }
+
+ function getLoginStatus() {
+ var url = "${statusUrl}";
+ jQuery.ajax({
+ url: url,
+ type: "GET",
+ dataType: "json",
+ async:true,
+ success: function(response) {
+ if (response.username != null) {
+ handleLoginSuccessfull(response.username);
+ } else {
+ showLogin();
+ }
+ }
+ }
+ );
+ }
+
+ function login() {
+ var postdata = {
+ username : document.getElementById('username').value,
+ password : document.getElementById('password').value
+ };
+
+ var url = "${loginUrl}";
+ jQuery.ajax({
+ url: url,
+ type: "POST",
+ data: postdata,
+ dataType: "json",
+ async:true,
+ success: function(response) {
+ if (response.result != null && response.result == 'ok') {
+ handleLoginSuccessfull(response.username);
+ } else {
+ var errorMsg = "An unexpected error occurred";
+ if (response.msg) {
+ errorMsg = response.msg;
+ }
+ var resultDiv = document.getElementById("result");
+ resultDiv.innerHTML = errorMsg;
+ }
+ }
+ }
+ );
+ }
+
+ function logout() {
+ var postdata = {
+ username : document.getElementById('username').value,
+ password : document.getElementById('password').value
+ };
+
+ var url = "${logoutUrl}";
+ jQuery.ajax({
+ url: url,
+ type: "POST",
+ data: postdata,
+ dataType: "json",
+ async:true
+ }
+ );
+ }
+
+ function denyAccess() {
+ logout();
+ showAccessDenied();
+ }
+
+ function handleLoginSuccessfull(username) {
+ showGrantAccess();
+ document.getElementById("welcome_username").innerHTML = "Welcome <b>" +
username + "</b>!";
+ }
+
+ function submitenter(field, e) {
+ var keycode;
+ if (window.event) {
+ keycode = window.event.keyCode;
+ } else if (e) {
+ keycode = e.which;
+ } else {
+ return true;
+ }
+
+ if (keycode == 13) {
+ login();
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ getLoginStatus();
+</script>
Modified:
trunk/amdatu-authorization/login-service/src/main/java/org/amdatu/authorization/login/service/service/LoginServiceImpl.java
==============================================================================
---
trunk/amdatu-authorization/login-service/src/main/java/org/amdatu/authorization/login/service/service/LoginServiceImpl.java
(original)
+++
trunk/amdatu-authorization/login-service/src/main/java/org/amdatu/authorization/login/service/service/LoginServiceImpl.java
Fri Dec 10 14:13:42 2010
@@ -130,9 +130,9 @@
// First retrieve the user with this username
JSONObject jsonObject = new JSONObject();
try {
- User user = m_userAdmin.getUser(USER_NAME_CREDENTIAL_KEY,
username);
-
- if (user != null) {
+ Role userRole = m_userAdmin.getRole(username);
+ if (userRole != null && userRole.getType() == Role.USER) {
+ User user = (User) userRole;
if (user.hasCredential(PASSWORD_CREDENTIAL_KEY, password)) {
Authorization auth = m_userAdmin.getAuthorization(user);
Modified:
trunk/amdatu-core/config-filebased/src/main/resources/conf/org.amdatu.authentication.oauth.server.cfg
==============================================================================
---
trunk/amdatu-core/config-filebased/src/main/resources/conf/org.amdatu.authentication.oauth.server.cfg
(original)
+++
trunk/amdatu-core/config-filebased/src/main/resources/conf/org.amdatu.authentication.oauth.server.cfg
Fri Dec 10 14:13:42 2010
@@ -1,3 +1,4 @@
# The hostname and portnr
hostname=${server.hostname}
-portnr=${server.port}
\ No newline at end of file
+portnr=${server.port}
+authorizeurl=/oauth-server/jsp/authorize.jsp
\ No newline at end of file
Modified:
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/DummyInterface.java
==============================================================================
---
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/DummyInterface.java
(original)
+++
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/DummyInterface.java
Fri Dec 10 14:13:42 2010
@@ -16,6 +16,13 @@
*/
package org.amdatu.example.oauth.service;
+/**
+ * This dummy interface is necessary in the current Amdatu version since a
REST service MUST implement an interface
+ * to be registered successfully by the JAX-RS implementation (currently;
Apache Wink). It doesn't matter what
+ * interface is implemented, it can be any interface.
+ * See issue http://jira.amdatu.org/jira/browse/AMDATU-221
+ *
+ * @author ivol
+ */
public interface DummyInterface {
-
}
Modified:
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthGadgetsRegistrationServiceImpl.java
==============================================================================
---
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthGadgetsRegistrationServiceImpl.java
(original)
+++
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthGadgetsRegistrationServiceImpl.java
Fri Dec 10 14:13:42 2010
@@ -40,6 +40,7 @@
/**
* This service registers the oAuth example gadgets.
+ *
* @author ivol
*/
public class OAuthGadgetsRegistrationServiceImpl implements ResourceProvider,
ManagedService {
@@ -68,6 +69,7 @@
private Component m_httpContextComponent;
private String m_hostname;
private String m_portnr;
+
/**
* The init() method is invoked by the Felix dependency manager.
*/
@@ -76,10 +78,12 @@
m_httpContextComponent =
m_httpContextFactoryService.create(m_bundleContext, this);
if (m_hostname == null || m_portnr == null) {
- // FIXME: For some reason update() is only invoked the very first
time this service is created. When
- // you stop/start the bundle, updated() will not be invoked (at
all!) and so hostname and portnr remain
- // null.
- } else {
+ // TODO: update() is only invoked the very first time this service
is created. When you stop/start the bundle,
+ // updated() will not be invoked (at all!) and so hostname and
portnr remain null.
+ // This is a known issue in the Felix dependency manager.
+ // See http://jira.amdatu.org/jira/browse/AMDATU-174 and
https://issues.apache.org/jira/browse/FELIX-2696
+ }
+ else {
String baseUrl = "http://" + m_hostname + ":" + m_portnr;
String gadgetUrl = baseUrl + "/" + RESOURCE_ID +
"/jsp/3leggedOAuthGadget.jspf";
GadgetDefinition gadgetDef = new GadgetDefinition(gadgetUrl,
GadgetCategory.AMDATU_EXAMPLES, false);
@@ -117,14 +121,16 @@
return RESOURCE_ID;
}
+ @SuppressWarnings("unchecked")
public void updated(Dictionary dictionary) throws ConfigurationException {
if (dictionary != null) {
- checkAvailability(dictionary, new String[] {HOSTNAME, PORTNR});
+ checkAvailability(dictionary, new String[] { HOSTNAME, PORTNR });
m_hostname = (String) dictionary.get(HOSTNAME);
m_portnr = (String) dictionary.get(PORTNR);
}
}
+ @SuppressWarnings("unchecked")
private void checkAvailability(Dictionary dictionary, String[]
mandatoryKeys) throws ConfigurationException {
for (String mandatoryKey : mandatoryKeys) {
if (dictionary.get(mandatoryKey) == null) {
@@ -137,26 +143,44 @@
try {
if (m_consumerRegistry.getConsumer(CONSUMER_KEY) == null) {
m_consumerRegistry.addConsumer(new
InternalOAuthServiceConsumer());
- } else {
+ }
+ else {
m_consumerRegistry.updateConsumer(new
InternalOAuthServiceConsumer());
}
}
catch (ConsumerAlreadyExistsException e) {
- m_logService.log(LogService.LOG_DEBUG, "Could not properly add
service consumer '" + CONSUMER_KEY + "' in the service consumer registry");
+ m_logService.log(LogService.LOG_DEBUG, "Could not properly add
service consumer '" + CONSUMER_KEY
+ + "' in the service consumer registry");
}
catch (ConsumerRegistryStorageException e) {
- m_logService.log(LogService.LOG_DEBUG, "Could not properly add or
update service consumer '" + CONSUMER_KEY + "' in the service consumer
registry");
+ m_logService.log(LogService.LOG_DEBUG, "Could not properly add or
update service consumer '" + CONSUMER_KEY
+ + "' in the service consumer registry");
}
catch (ConsumerNotFoundException e) {
- m_logService.log(LogService.LOG_DEBUG, "Could not properly update
service consumer '" + CONSUMER_KEY + "' in the service consumer registry");
+ m_logService.log(LogService.LOG_DEBUG, "Could not properly update
service consumer '" + CONSUMER_KEY
+ + "' in the service consumer registry");
}
}
class InternalOAuthServiceConsumer implements OAuthServiceConsumer {
- public String getCallbackUrl() {return CONSUMER_CALLBACK_URL;}
- public String getConsumerKey() {return CONSUMER_KEY;}
- public String getConsumerSecret() {return CONSUMER_SECRET;}
- public String getName() {return CONSUMER_NAME;}
- public Map<String, String> getProperties() {return null;}
+ public String getCallbackUrl() {
+ return CONSUMER_CALLBACK_URL;
+ }
+
+ public String getConsumerKey() {
+ return CONSUMER_KEY;
+ }
+
+ public String getConsumerSecret() {
+ return CONSUMER_SECRET;
+ }
+
+ public String getName() {
+ return CONSUMER_NAME;
+ }
+
+ public Map<String, String> getProperties() {
+ return null;
+ }
}
}
Modified:
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthProtectedResource.java
==============================================================================
---
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthProtectedResource.java
(original)
+++
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthProtectedResource.java
Fri Dec 10 14:13:42 2010
@@ -20,9 +20,11 @@
import java.net.URISyntaxException;
import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
+import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@@ -52,6 +54,10 @@
@GET
@Produces( { MediaType.TEXT_HTML })
public Response getResource(@Context HttpServletRequest request) {
+ // Disable cache completely
+ CacheControl cc = new CacheControl();
+ cc.setNoCache(true);
+
try {
String response = "<p>oAuth validation successfull. OAuth
parameters received by service provider:<br/><br/>";
response += "<table><tr><th align=\"left\">parameter</th><th
align=\"left\">value</th></tr>";
@@ -63,16 +69,19 @@
response += "<tr><td>consumer secret</td><td>" +
accessor.consumer.consumerSecret + "</td></tr>";
response += "<tr><td>consumer callback url</td><td>" +
accessor.consumer.callbackURL + "</td></tr>";
response += "</table></p>";
- return Response.ok(response, MediaType.TEXT_HTML).build();
+ return Response.ok(response,
MediaType.TEXT_HTML).cacheControl(cc).build();
}
catch (IOException e) {
- return Response.serverError().build();
+ return Response.serverError().cacheControl(cc).build();
}
catch (OAuthException e) {
- return Response.serverError().build();
+ // In case an oAuth exception occures, this means that someone
tries to access this resource
+ // with an invalid token. Return a 401 to allow the service
consumer to (re)initiate the
+ // oAuth dance.
+ return
Response.status(HttpServletResponse.SC_UNAUTHORIZED).cacheControl(cc).build();
}
catch (URISyntaxException e) {
- return Response.serverError().build();
+ return Response.serverError().cacheControl(cc).build();
}
}
Modified:
trunk/amdatu-web/httpcontext/src/main/java/org/amdatu/web/httpcontext/BasicHttpSession.java
==============================================================================
---
trunk/amdatu-web/httpcontext/src/main/java/org/amdatu/web/httpcontext/BasicHttpSession.java
(original)
+++
trunk/amdatu-web/httpcontext/src/main/java/org/amdatu/web/httpcontext/BasicHttpSession.java
Fri Dec 10 14:13:42 2010
@@ -20,8 +20,8 @@
import java.util.Map;
import javax.servlet.ServletRequest;
-import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
/**
* This is a temporary basic implementation of a http session. It is needed
because http sessions
@@ -53,19 +53,14 @@
public synchronized static BasicHttpSession getSession(ServletRequest
request) {
if (request instanceof HttpServletRequest) {
- if (((HttpServletRequest) request).getCookies() != null) {
- for (Cookie cookie : ((HttpServletRequest)
request).getCookies()) {
- if ("jsessionid".equalsIgnoreCase(cookie.getName())) {
- String sessionkey = cookie.getValue();
- if (m_sessions.get(sessionkey) != null) {
- return m_sessions.get(sessionkey);
- } else {
- BasicHttpSession session = new BasicHttpSession();
- m_sessions.put(sessionkey, session);
- return session;
- }
- }
- }
+ HttpSession httpSession = ((HttpServletRequest)
request).getSession(true);
+ String sessionId = httpSession.getId();
+ if (m_sessions.get(sessionId) != null) {
+ return m_sessions.get(sessionId);
+ } else {
+ BasicHttpSession session = new BasicHttpSession();
+ m_sessions.put(sessionId, session);
+ return session;
}
}
return null;
Modified: trunk/integration-tests/pom.xml
==============================================================================
--- trunk/integration-tests/pom.xml (original)
+++ trunk/integration-tests/pom.xml Fri Dec 10 14:13:42 2010
@@ -134,6 +134,13 @@
<type>bundle</type>
</dependency>
<dependency>
+ <groupId>org.amdatu.core</groupId>
+ <artifactId>useradminstore-fs</artifactId>
+ <version>${platform.version}</version>
+ <scope>test</scope>
+ <type>bundle</type>
+ </dependency>
+ <dependency>
<groupId>org.amdatu.web.rest</groupId>
<artifactId>jaxrs</artifactId>
<version>${platform.version}</version>
Modified:
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/ConfigProvider.java
==============================================================================
---
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/ConfigProvider.java
(original)
+++
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/ConfigProvider.java
Fri Dec 10 14:13:42 2010
@@ -21,13 +21,19 @@
import java.net.URL;
import java.util.Properties;
+import junit.framework.Assert;
+
import org.amdatu.authentication.oauth.server.OAuthServerConfig;
+import org.amdatu.authorization.login.service.LoginService;
import org.amdatu.cassandra.application.CassandraConfigurationService;
import org.amdatu.core.config.templates.ConfigTemplateManager;
import org.amdatu.core.tenant.TenantStorageProvider;
import org.amdatu.opensocial.shindig.ShindigService;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
+import org.osgi.service.useradmin.Role;
+import org.osgi.service.useradmin.User;
+import org.osgi.service.useradmin.UserAdmin;
/**
* This class provides the configurations for the bundles under test.
@@ -41,6 +47,9 @@
// NB: Due to issue https://issues.apache.org/jira/browse/FELIX-2714 we
must use the default port for testing
public final static String PORTNR = "8080";
public final static String SECURE_PORTNR = "8081";
+
+ public final static String TEST_USERNAME = "georged";
+ public final static String TEST_PASSWORD = "georged";
public void addLogConfig(ConfigurationAdmin configAdmin) throws
IOException {
Configuration config =
configAdmin.getConfiguration("org.amdatu.core.loghandler", null);
@@ -158,7 +167,7 @@
*/
}
- public void addUserAdminConfig(ConfigurationAdmin configAdmin) throws
IOException {
+ public void addFSUserAdminConfig(ConfigurationAdmin configAdmin) throws
IOException {
Configuration config =
configAdmin.getConfiguration("org.amdatu.core.useradminstore-fs", null);
Properties properties = new Properties();
properties.put(TenantStorageProvider.DATA_DIRECTORY,
"work/useradminstore");
@@ -170,9 +179,22 @@
Properties properties = new Properties();
properties.put(OAuthServerConfig.HOSTNAME, ConfigProvider.HOSTNAME);
properties.put(OAuthServerConfig.PORTNR, ConfigProvider.PORTNR);
+ properties.put(OAuthServerConfig.AUTHORIZE_URL,
"/oauth-server/jsp/authorize.jsp");
config.update(properties);
}
+
+ @SuppressWarnings("unchecked")
+ public void addTestUser(UserAdmin userAdmin) {
+ User user = (User) userAdmin.createRole(TEST_USERNAME, Role.USER);
+ user.getCredentials().put(LoginService.PASSWORD_CREDENTIAL_KEY,
TEST_PASSWORD);
+ Assert.assertTrue("Test user '" + TEST_USERNAME + "' could not be
created", userAdmin.getRole(TEST_USERNAME) != null);
+ }
+ public void removeTestUser(UserAdmin userAdmin) {
+ userAdmin.removeRole(TEST_USERNAME);
+ Assert.assertFalse("Test user '" + TEST_USERNAME + "' could not be
removed", userAdmin.getRole(TEST_USERNAME) != null);
+ }
+
/**
* Wait until the service at the specified URL returns the specified
response code with a timeout as specified.
*
Modified:
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/IntegrationTestBase.java
==============================================================================
---
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/IntegrationTestBase.java
(original)
+++
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/IntegrationTestBase.java
Fri Dec 10 14:13:42 2010
@@ -299,6 +299,10 @@
protected static MavenArtifactProvisionOption
amdatuUserAdminCassandraStore() {
return
mavenBundle().groupId("org.amdatu.cassandra").artifactId("useradminstore").versionAsInProject();
}
+
+ protected static MavenArtifactProvisionOption amdatuUserAdminFSStore() {
+ return
mavenBundle().groupId("org.amdatu.core").artifactId("useradminstore-fs").versionAsInProject();
+ }
protected static MavenArtifactProvisionOption amdatuTenantService() {
return
mavenBundle().groupId("org.amdatu.core").artifactId("tenant").versionAsInProject();
Modified:
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/OAuthTestBase.java
==============================================================================
---
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/OAuthTestBase.java
(original)
+++
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/OAuthTestBase.java
Fri Dec 10 14:13:42 2010
@@ -16,55 +16,70 @@
*/
package org.amdatu.test.integration.base;
+import static org.amdatu.test.integration.base.ConfigProvider.HOSTNAME;
+import static org.amdatu.test.integration.base.ConfigProvider.PORTNR;
+import static org.amdatu.test.integration.base.ConfigProvider.TEST_PASSWORD;
+import static org.amdatu.test.integration.base.ConfigProvider.TEST_USERNAME;
import static org.ops4j.pax.exam.CoreOptions.provision;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Dictionary;
+import java.util.HashMap;
import java.util.Hashtable;
+import java.util.Map;
import javax.servlet.Servlet;
-import org.amdatu.authentication.oauth.api.OAuthServiceConsumer;
import org.amdatu.authentication.oauth.api.OAuthServiceConsumerRegistry;
import org.amdatu.authentication.oauth.api.OAuthServiceProvider;
import org.amdatu.authentication.oauth.server.OAuthRequestTokenServlet;
import org.amdatu.authentication.oauth.server.OAuthTokenProvider;
+import org.amdatu.authorization.login.service.LoginService;
import org.amdatu.test.integration.mock.OAuthProtectedTestServlet;
-import org.amdatu.test.integration.mock.OAuthTestConsumer;
+import org.apache.commons.httpclient.Header;
+import org.apache.commons.httpclient.HeaderElement;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.felix.dm.Component;
import org.apache.felix.dm.DependencyManager;
import org.apache.http.HttpStatus;
+import org.junit.Assert;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
+import org.ops4j.pax.useradmin.service.spi.StorageProvider;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.http.HttpService;
import org.osgi.service.log.LogService;
+import org.osgi.service.useradmin.UserAdmin;
public class OAuthTestBase extends IntegrationTestBase {
- protected final String TEST_USERID = "ivol";
-
protected volatile LogService m_logService;
protected volatile OAuthServiceProvider m_oAuthServiceProvider;
protected volatile ConfigurationAdmin m_configAdmin;
protected volatile DependencyManager m_dependencyManager;
protected volatile OAuthTokenProvider m_tokenProvider;
protected volatile OAuthServiceConsumerRegistry m_consumerRegistry;
+ protected volatile UserAdmin m_userAdmin;
+ private HeaderElement m_cookieHeaderElement;
+
@Configuration
public Option[] configure() {
return super.configure();
}
-
+
protected void initConfiguration() throws IOException {
m_configAdmin = getService(ConfigurationAdmin.class);
-
+
// Add cassandra and templates configs
ConfigProvider configProvider = new ConfigProvider();
configProvider.addFelixHttpServiceConfig(m_configAdmin);
configProvider.addOAuthConfig(m_configAdmin);
configProvider.addLogConfig(m_configAdmin);
configProvider.addFSConsumerStoreConfig(m_configAdmin);
+ configProvider.addFSUserAdminConfig(m_configAdmin);
}
protected Component[] getDependencies(DependencyManager manager) {
@@ -88,6 +103,9 @@
.add(manager.createServiceDependency().setService(ConfigurationAdmin.class).setRequired(true))
.add(manager.createServiceDependency().setService(OAuthServiceConsumerRegistry.class).setRequired(true))
.add(manager.createServiceDependency().setService(HttpService.class).setRequired(true))
+
.add(manager.createServiceDependency().setService(UserAdmin.class).setRequired(true))
+
.add(manager.createServiceDependency().setService(LoginService.class).setRequired(true))
+
.add(manager.createServiceDependency().setService(StorageProvider.class).setRequired(true))
.add(manager.createServiceDependency().setService(LogService.class).setRequired(true));
return new Component[] { servletComponent, testComponent };
@@ -105,6 +123,8 @@
paxSwissbox(),
ops4jBaseLang(),
json(),
+ paxUserAdmin(),
+ amdatuUserAdminFSStore(),
amdatuHttpContext(),
amdatuJaxRs(),
amdatuWink(),
@@ -112,17 +132,55 @@
amdatuOAuthClient(),
amdatuOAuthServer(),
amdatuOAuthConsumerRegistry(),
- amdatuJspSupport());
+ amdatuJspSupport(),
+ amdatuLogin());
}
-
+
protected void waitForOAuthServlets() throws MalformedURLException,
IOException {
// First wait for the request servlet to become available
- m_logService.log(LogService.LOG_DEBUG, "Waiting for '" +
m_oAuthServiceProvider.getRequestTokenURL() + "' to come available...");
- waitForURL( m_oAuthServiceProvider.getRequestTokenURL(),
HttpStatus.SC_UNAUTHORIZED);
- m_logService.log(LogService.LOG_DEBUG, "Waiting for '" +
m_oAuthServiceProvider.getAuthorizeTokenURL() + "' to come available...");
- waitForURL( m_oAuthServiceProvider.getAuthorizeTokenURL(),
HttpStatus.SC_UNAUTHORIZED);
- m_logService.log(LogService.LOG_DEBUG, "Waiting for '" +
m_oAuthServiceProvider.getAccessTokenURL() + "' to come available...");
- waitForURL( m_oAuthServiceProvider.getAccessTokenURL(),
HttpStatus.SC_UNAUTHORIZED);
+ m_logService.log(LogService.LOG_DEBUG, "Waiting for '" +
m_oAuthServiceProvider.getRequestTokenURL()
+ + "' to come available...");
+ waitForURL(m_oAuthServiceProvider.getRequestTokenURL(),
HttpStatus.SC_UNAUTHORIZED);
+ m_logService.log(LogService.LOG_DEBUG, "Waiting for '" +
m_oAuthServiceProvider.getAuthorizeTokenURL()
+ + "' to come available...");
+ waitForURL(m_oAuthServiceProvider.getAuthorizeTokenURL(),
HttpStatus.SC_UNAUTHORIZED);
+ m_logService.log(LogService.LOG_DEBUG, "Waiting for '" +
m_oAuthServiceProvider.getAccessTokenURL()
+ + "' to come available...");
+ waitForURL(m_oAuthServiceProvider.getAccessTokenURL(),
HttpStatus.SC_UNAUTHORIZED);
m_logService.log(LogService.LOG_DEBUG, "oAuth servlets available");
}
+
+ protected void login() throws HttpException, IOException {
+ String loginUrl = "http://" + HOSTNAME + ":" + PORTNR +
"/rest/services/authorization/authorization/login";
+ HttpClient httpClient = new HttpClient();
+ PostMethod postMethod = null;
+ try {
+ postMethod = new PostMethod(loginUrl);
+ postMethod.addParameter("username", TEST_USERNAME);
+ postMethod.addParameter("password", TEST_PASSWORD);
+ postMethod.addRequestHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
+ int status = httpClient.executeMethod(postMethod);
+ Header cookieHeader = postMethod.getResponseHeader("Set-Cookie");
+ HeaderElement[] headerElements = cookieHeader.getElements();
+ for (HeaderElement headerElement : headerElements) {
+ if ("jsessionid".equalsIgnoreCase(headerElement.getName())) {
+ m_logService.log(LogService.LOG_DEBUG, "Login service set
cookie header " + headerElement.getName()
+ + "=" + headerElement.getValue());
+ m_cookieHeaderElement = headerElement;
+ }
+ }
+ Assert.assertTrue("Login failed using Amdatu account '" +
TEST_USERNAME + "', response code=" + status,
+ status == HttpStatus.SC_OK);
+ }
+ finally {
+ postMethod.releaseConnection();
+ }
+ }
+
+ protected Map<String, String> getCookieHeader() {
+ Map<String, String> requestHeaders = new HashMap<String, String>();
+ String header = m_cookieHeaderElement.getName() + "=" +
m_cookieHeaderElement.getValue();
+ requestHeaders.put("Cookie", header);
+ return requestHeaders;
+ }
}
Modified:
trunk/integration-tests/src/test/java/org/amdatu/test/integration/tests/OAuthThreeLeggedTest.java
==============================================================================
---
trunk/integration-tests/src/test/java/org/amdatu/test/integration/tests/OAuthThreeLeggedTest.java
(original)
+++
trunk/integration-tests/src/test/java/org/amdatu/test/integration/tests/OAuthThreeLeggedTest.java
Fri Dec 10 14:13:42 2010
@@ -16,8 +16,13 @@
*/
package org.amdatu.test.integration.tests;
+import static org.amdatu.test.integration.base.ConfigProvider.TEST_USERNAME;
import static
org.amdatu.test.integration.mock.OAuthProtectedTestServlet.OAUTH_TYPE_PARAM;
import static
org.amdatu.test.integration.mock.OAuthProtectedTestServlet.OAUTH_TYPE_THREE_LEGGED;
+
+import java.util.HashMap;
+import java.util.Map;
+
import net.oauth.OAuthAccessor;
import net.oauth.OAuthMessage;
@@ -28,12 +33,12 @@
import org.amdatu.test.integration.base.OAuthTestBase;
import org.amdatu.test.integration.mock.OAuthProtectedTestServlet;
import org.amdatu.test.integration.mock.OAuthTestConsumer;
+import org.apache.commons.httpclient.HeaderElement;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.osgi.service.log.LogService;
-
/**
* Test class for 3-legged oAuth
*
@@ -60,14 +65,19 @@
m_logService.log(LogService.LOG_DEBUG, "*** Step 3: Generate request
token ***");
OAuthAccessor accessor = createRequestToken(consumerClient);
- // Step 4: Authorize the request token for a user we define
- m_logService.log(LogService.LOG_DEBUG, "*** Step 4: Authorize the
request token ***");
- String callback = userClient.authorizeToken(accessor, TEST_USERID);
+ // Step 4: Log in using an Amdatu account, just after creating it
+ m_logService.log(LogService.LOG_DEBUG, "*** Step 4: Log in with Amdatu
account '" + TEST_USERNAME + "' ***");
+ new ConfigProvider().addTestUser(m_userAdmin);
+ login();
+
+ // Step 5: Authorize the request token for a user we define
+ m_logService.log(LogService.LOG_DEBUG, "*** Step 5: Authorize the
request token ***");
+ String callback = userClient.authorizeToken(accessor,
getCookieHeader());
Assert.assertTrue(callback.startsWith(OAuthTestConsumer.DEFAULT_CALLBACK_URL +
"?oauth_token="));
m_logService.log(LogService.LOG_DEBUG, "Callback URL received: " +
callback);
- // Step 5: Exchange our request token for an access token
- m_logService.log(LogService.LOG_DEBUG, "*** Step 5: Get access token
***");
+ // Step 6: Exchange our request token for an access token
+ m_logService.log(LogService.LOG_DEBUG, "*** Step 6: Get access token
***");
OAuthMessage message = consumerClient.getAccessToken(accessor);
accessor.accessToken = message.getToken();
accessor.tokenSecret = message.getParameter("oauth_token_secret");
@@ -75,18 +85,18 @@
m_logService.log(LogService.LOG_DEBUG, "Access token received: " +
accessor.accessToken + ", with secret "
+ accessor.tokenSecret);
- // Step 6: Access a protected resource
- m_logService.log(LogService.LOG_DEBUG, "*** Step 6: Access protected
resource ***");
- String url =
- "http://" + ConfigProvider.HOSTNAME + ":" + ConfigProvider.PORTNR
+ OAuthProtectedTestServlet.SERVLET_ALIAS;
+ // Step 7: Access a protected resource
+ m_logService.log(LogService.LOG_DEBUG, "*** Step 7: Access protected
resource ***");
+ String url = "http://" + ConfigProvider.HOSTNAME + ":" +
ConfigProvider.PORTNR + OAuthProtectedTestServlet.SERVLET_ALIAS;
url += "?" + OAUTH_TYPE_PARAM + "=" + OAUTH_TYPE_THREE_LEGGED;
message = consumerClient.accessResource(accessor, url, "GET");
String body = message.readBodyAsString();
m_logService.log(LogService.LOG_DEBUG, "Protected resource returns
response: '" + body + "'");
- Assert.assertTrue(body.equals("userid=" + TEST_USERID));
-
- // Step 7: Remove the consumer
+ Assert.assertTrue(body.equals("userid=" + TEST_USERNAME));
+
+ // Step 8: Cleanup; remove the consumer and our test user
m_consumerRegistry.removeConsumer(consumer);
+ new ConfigProvider().removeTestUser(m_userAdmin);
}
// Step 3: Generate a request token for our service consumer
Modified:
trunk/integration-tests/src/test/java/org/amdatu/test/integration/tests/OAuthTwoLeggedTest.java
==============================================================================
---
trunk/integration-tests/src/test/java/org/amdatu/test/integration/tests/OAuthTwoLeggedTest.java
(original)
+++
trunk/integration-tests/src/test/java/org/amdatu/test/integration/tests/OAuthTwoLeggedTest.java
Fri Dec 10 14:13:42 2010
@@ -19,6 +19,7 @@
import static
org.amdatu.test.integration.mock.OAuthProtectedTestServlet.OAUTH_TYPE_PARAM;
import static
org.amdatu.test.integration.mock.OAuthProtectedTestServlet.OAUTH_TYPE_TWO_LEGGED;
import static
org.amdatu.test.integration.mock.OAuthProtectedTestServlet.SERVLET_ALIAS;
+import static org.amdatu.test.integration.base.ConfigProvider.*;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthMessage;
@@ -48,8 +49,8 @@
// Step 2: validate that the user id has not yet been added to the
consumer registry
Assert.assertFalse(
- "Userid '" + TEST_USERID + "' already added to allowed userids in
the service consumer registry",
- m_consumerRegistry.hasResourceAccess(consumer, TEST_USERID));
+ "Userid '" + TEST_USERNAME + "' already added to allowed userids
in the service consumer registry",
+ m_consumerRegistry.hasResourceAccess(consumer, TEST_USERNAME));
// Step 3: perform a 3-legged oAuth dance for user 'ivol'
// Step 3a: Create an OAuthClient for our Amdatu OAuth server
@@ -60,13 +61,18 @@
// Step 3b: Generate a request token for our service consumer
m_logService.log(LogService.LOG_DEBUG, "*** Step 3b: Generate request
token ***");
OAuthAccessor accessor = createRequestToken(consumerClient);
+
+ // Step 3c: Log in using an Amdatu account, but create that account
first
+ m_logService.log(LogService.LOG_DEBUG, "*** Step 3c: Log in with
Amdatu account '" + TEST_USERNAME + "' ***");
+ new ConfigProvider().addTestUser(m_userAdmin);
+ login();
+
+ // Step 3d: Authorize the request token for a user we define
+ m_logService.log(LogService.LOG_DEBUG, "*** Step 3d: Authorize the
request token ***");
+ userClient.authorizeToken(accessor, getCookieHeader());
- // Step 3c: Authorize the request token for a user we define
- m_logService.log(LogService.LOG_DEBUG, "*** Step 3c: Authorize the
request token ***");
- userClient.authorizeToken(accessor, TEST_USERID);
-
- // Step 3d: Exchange our request token for an access token
- m_logService.log(LogService.LOG_DEBUG, "*** Step 3d: Get access token
***");
+ // Step 3e: Exchange our request token for an access token
+ m_logService.log(LogService.LOG_DEBUG, "*** Step 3e: Get access token
***");
OAuthMessage message = consumerClient.getAccessToken(accessor);
accessor.accessToken = message.getToken();
accessor.tokenSecret = message.getParameter("oauth_token_secret");
@@ -74,8 +80,8 @@
// Step 4: validate if the user id has been added to the consumer
registry
Assert.assertTrue(
- "Userid '" + TEST_USERID + "', not added to allowed userids in the
service consumer registry",
- m_consumerRegistry.hasResourceAccess(consumer, TEST_USERID));
+ "Userid '" + TEST_USERNAME + "', not added to allowed userids in
the service consumer registry",
+ m_consumerRegistry.hasResourceAccess(consumer, TEST_USERNAME));
// Step 5: Now access a 2-legged protected resource
String url = "http://" + ConfigProvider.HOSTNAME + ":" +
ConfigProvider.PORTNR + SERVLET_ALIAS;
@@ -83,17 +89,18 @@
message = consumerClient.accessResource(accessor, url, "GET");
String body = message.readBodyAsString();
m_logService.log(LogService.LOG_DEBUG, "Protected resource returns
response: '" + body + "'");
- Assert.assertTrue(body.equals("userid=" + TEST_USERID));
+ Assert.assertTrue(body.equals("userid=" + TEST_USERNAME));
// Step 7: Withdraw the access, then try to access the protected
resource again
- m_consumerRegistry.withdrawResourceAccess(consumer, TEST_USERID);
+ m_consumerRegistry.withdrawResourceAccess(consumer, TEST_USERNAME);
message = consumerClient.accessResource(accessor, url, "GET");
body = message.readBodyAsString();
m_logService.log(LogService.LOG_DEBUG, "Protected resource returns
response: '" + body + "'");
Assert.assertTrue(body.equals("access denied"));
- // Step 8: Remove the consumer
- m_consumerRegistry.removeConsumer(consumer);
+ // Step 8: Cleanup; remove the consumer and our test user
+ m_consumerRegistry.removeConsumer(consumer);
+ new ConfigProvider().removeTestUser(m_userAdmin);
}
// Step 1c: Generate a request token for our service consumer