net.oauth.signature.OAuthSignatureMethod Java Examples

The following examples show how to use net.oauth.signature.OAuthSignatureMethod. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PEMReader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Read the lines between BEGIN and END marker and convert
 * the Base64 encoded content into binary byte array.
 * 
 * @return DER encoded octet stream
 * @throws IOException
 */
private byte[] readBytes(BufferedReader reader, String endMarker) throws IOException
{
    String          line = null;
    StringBuffer    buf = new StringBuffer();

    while ((line = reader.readLine()) != null)
    {
        if (line.indexOf(endMarker) != -1) {

            return OAuthSignatureMethod.decodeBase64(buf.toString());
        }

        buf.append(line.trim());        
    }

    throw new IOException("Invalid PEM file: No end marker");
}
 
Example #2
Source File: PEMReader.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Read the lines between BEGIN and END marker and convert
 * the Base64 encoded content into binary byte array.
 * 
 * @return DER encoded octet stream
 * @throws IOException
 */
private byte[] readBytes(BufferedReader reader, String endMarker) throws IOException
{
    String          line = null;
    StringBuffer    buf = new StringBuffer();

    while ((line = reader.readLine()) != null)
    {
        if (line.indexOf(endMarker) != -1) {

            return OAuthSignatureMethod.decodeBase64(buf.toString());
        }

        buf.append(line.trim());        
    }

    throw new IOException("Invalid PEM file: No end marker");
}
 
Example #3
Source File: BasicLTIUtil.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/** 
        * getOAuthURL - Form a GET request signed by OAuth
 * @param method
 * @param url
 * @param oauth_consumer_key
 * @param oauth_secret
 * @param signature
 */
public static String getOAuthURL(String method, String url, 
	String oauth_consumer_key, String oauth_secret, String signature)
{
	OAuthMessage om = new OAuthMessage(method, url, null);
	om.addParameter(OAuth.OAUTH_CONSUMER_KEY, oauth_consumer_key);
	if ( signature == null ) signature = OAuth.HMAC_SHA1;
	om.addParameter(OAuth.OAUTH_SIGNATURE_METHOD, signature);
	om.addParameter(OAuth.OAUTH_VERSION, "1.0");
	om.addParameter(OAuth.OAUTH_TIMESTAMP, new Long((new Date().getTime()) / 1000).toString());
	om.addParameter(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());

	OAuthConsumer oc = new OAuthConsumer(null, oauth_consumer_key, oauth_secret, null);
	try {
	    OAuthSignatureMethod osm = OAuthSignatureMethod.newMethod(signature, new OAuthAccessor(oc));
	    osm.sign(om);
	    url = OAuth.addParameters(url, om.getParameters());
	    return url;
	} catch (Exception e) {
		log.error(e.getMessage(), e);
		return null;
	}
}
 
Example #4
Source File: BasicLTIUtil.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/** 
        * getOAuthURL - Form a GET request signed by OAuth
 * @param method
 * @param url
 * @param oauth_consumer_key
 * @param oauth_secret
 * @param signature
 */
public static String getOAuthURL(String method, String url, 
	String oauth_consumer_key, String oauth_secret, String signature)
{
	OAuthMessage om = new OAuthMessage(method, url, null);
	om.addParameter(OAuth.OAUTH_CONSUMER_KEY, oauth_consumer_key);
	if ( signature == null ) signature = OAuth.HMAC_SHA1;
	om.addParameter(OAuth.OAUTH_SIGNATURE_METHOD, signature);
	om.addParameter(OAuth.OAUTH_VERSION, "1.0");
	om.addParameter(OAuth.OAUTH_TIMESTAMP, new Long((new Date().getTime()) / 1000).toString());
	om.addParameter(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());

	OAuthConsumer oc = new OAuthConsumer(null, oauth_consumer_key, oauth_secret, null);
	try {
	    OAuthSignatureMethod osm = OAuthSignatureMethod.newMethod(signature, new OAuthAccessor(oc));
	    osm.sign(om);
	    url = OAuth.addParameters(url, om.getParameters());
	    return url;
	} catch (Exception e) {
		log.error(e.getMessage(), e);
		return null;
	}
}
 
Example #5
Source File: PEMReader.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Read the lines between BEGIN and END marker and convert
 * the Base64 encoded content into binary byte array.
 * 
 * @return DER encoded octet stream
 * @throws IOException
 */
private byte[] readBytes(BufferedReader reader, String endMarker) throws IOException
{
    String          line = null;
    StringBuffer    buf = new StringBuffer();

    while ((line = reader.readLine()) != null)
    {
        if (line.indexOf(endMarker) != -1) {

            return OAuthSignatureMethod.decodeBase64(buf.toString());
        }

        buf.append(line.trim());        
    }

    throw new IOException("Invalid PEM file: No end marker");
}
 
Example #6
Source File: WaveService.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a URL that contains the necessary OAuth query parameters for the
 * given JSON string.
 *
 * The required OAuth parameters are:
 * <ul>
 * <li>oauth_body_hash</li>
 * <li>oauth_consumer_key</li>
 * <li>oauth_signature_method</li>
 * <li>oauth_timestamp</li>
 * <li>oauth_nonce</li>
 * <li>oauth_version</li>
 * <li>oauth_signature</li>
 * </ul>
 *
 * @param jsonBody the JSON string to construct the URL from.
 * @param rpcServerUrl the URL of the handler that services the JSON-RPC
 *        request.
 * @param accessor the OAuth accessor used to create the signed string.
 * @return a URL for the given JSON string, and the required OAuth parameters.
 */
public static String createOAuthUrlString(
    String jsonBody, String rpcServerUrl, OAuthAccessor accessor)
    throws IOException, URISyntaxException, OAuthException {
  OAuthMessage message =
      new OAuthMessage(POST, rpcServerUrl, Collections.<SimpleEntry<String, String>>emptyList());

  // Compute the hash of the body.
  byte[] rawBody = jsonBody.getBytes(UTF_8);
  byte[] hash = DigestUtils.sha(rawBody);
  byte[] encodedHash = Base64.encodeBase64(hash);
  message.addParameter(OAUTH_BODY_HASH, new String(encodedHash, UTF_8));

  // Add other parameters.

  message.addRequiredParameters(accessor);
  if (LOG.isLoggable(Level.FINE)) {
    LOG.fine("Signature base string: " + OAuthSignatureMethod.getBaseString(message));
  }

  // Construct the resulting URL.
  StringBuilder sb = new StringBuilder(rpcServerUrl);
  char connector = '?';
  for (Map.Entry<String, String> p : message.getParameters()) {
    if (!p.getKey().equals(jsonBody)) {
      sb.append(connector);
      sb.append(URLEncoder.encode(p.getKey(), UTF_8));
      sb.append('=');
      sb.append(URLEncoder.encode(p.getValue(), UTF_8));
      connector = '&';
    }
  }
  return sb.toString();
}
 
Example #7
Source File: BasicLTIUtilTest.java    From basiclti-util-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateMessagePass() throws Exception {

    SimpleOAuthValidator sov = Mockito.mock(SimpleOAuthValidator.class);
    PowerMockito.whenNew(SimpleOAuthValidator.class).withNoArguments().thenReturn(sov);
    Mockito.doNothing().when(sov).validateMessage(Matchers.any(OAuthMessage.class), Matchers.any(OAuthAccessor.class));
    PowerMockito.mockStatic(OAuthSignatureMethod.class);
    PowerMockito.when(OAuthSignatureMethod.getBaseString(Matchers.any(OAuthMessage.class))).thenReturn("");
    
    HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
    Mockito.when(req.getParameter("user_id")).thenReturn("pgray");
    Mockito.when(req.getParameter("roles")).thenReturn("instructor, teacher,administrator");
    Mockito.when(req.getParameter("lti_version")).thenReturn("lpv1");
    Mockito.when(req.getParameter("lti_message_type")).thenReturn("lti");
    Mockito.when(req.getParameter("resource_link_id")).thenReturn("12345");
    Mockito.when(req.getParameter("context_id")).thenReturn("9876");
    Mockito.when(req.getParameter("launch_presentation_return_url")).thenReturn("http://example.com/return");
    Mockito.when(req.getParameter("tool_consumer_instance_guid")).thenReturn("instance_id");

    LtiVerificationResult result = BasicLTIUtil.validateMessage(req, "https://example.com/lti-launch", "secret1");        

    Assert.assertEquals(null, result.getError());
    Assert.assertEquals(Boolean.TRUE, result.getSuccess());
    Assert.assertNotNull(result.getLtiLaunchResult());
    
    Assert.assertEquals("pgray", result.getLtiLaunchResult().getUser().getId());
    Assert.assertEquals(3, result.getLtiLaunchResult().getUser().getRoles().size());
    Assert.assertTrue(result.getLtiLaunchResult().getUser().getRoles().contains("instructor"));
    Assert.assertTrue(result.getLtiLaunchResult().getUser().getRoles().contains("teacher"));
    Assert.assertTrue(result.getLtiLaunchResult().getUser().getRoles().contains("administrator"));
    
    Assert.assertEquals("lpv1", result.getLtiLaunchResult().getVersion());
    Assert.assertEquals("lti", result.getLtiLaunchResult().getMessageType());
    Assert.assertEquals("12345", result.getLtiLaunchResult().getResourceLinkId());
    Assert.assertEquals("9876", result.getLtiLaunchResult().getContextId());
    Assert.assertEquals("http://example.com/return", result.getLtiLaunchResult().getLaunchPresentationReturnUrl());
    Assert.assertEquals("instance_id", result.getLtiLaunchResult().getToolConsumerInstanceGuid());
    
}
 
Example #8
Source File: BasicLTIUtilTest.java    From basiclti-util-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateMessageFailOnValidateMessageURISyntaxException() throws Exception {

    SimpleOAuthValidator sov = Mockito.mock(SimpleOAuthValidator.class);
    PowerMockito.whenNew(SimpleOAuthValidator.class).withNoArguments().thenReturn(sov);
    Mockito.doThrow(new URISyntaxException("failed", "failed")).when(sov).validateMessage(Matchers.any(OAuthMessage.class), Matchers.any(OAuthAccessor.class));
    PowerMockito.mockStatic(OAuthSignatureMethod.class);
    PowerMockito.when(OAuthSignatureMethod.getBaseString(Matchers.any(OAuthMessage.class))).thenReturn("");

    LtiVerificationResult result = BasicLTIUtil.validateMessage(Mockito.mock(HttpServletRequest.class), "https://example.com/lti-launch", "secret");        

    Assert.assertEquals(LtiError.BAD_REQUEST, result.getError());
    Assert.assertEquals(Boolean.FALSE, result.getSuccess());
    Assert.assertEquals(null, result.getLtiLaunchResult());
}
 
Example #9
Source File: BasicLTIUtilTest.java    From basiclti-util-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateMessageFailOnValidateMessageOAuthException() throws Exception {

    SimpleOAuthValidator sov = Mockito.mock(SimpleOAuthValidator.class);
    PowerMockito.whenNew(SimpleOAuthValidator.class).withNoArguments().thenReturn(sov);
    Mockito.doThrow(new OAuthException("failed")).when(sov).validateMessage(Matchers.any(OAuthMessage.class), Matchers.any(OAuthAccessor.class));
    PowerMockito.mockStatic(OAuthSignatureMethod.class);
    PowerMockito.when(OAuthSignatureMethod.getBaseString(Matchers.any(OAuthMessage.class))).thenReturn("");

    LtiVerificationResult result = BasicLTIUtil.validateMessage(Mockito.mock(HttpServletRequest.class), "https://example.com/lti-launch", "secret");

    Assert.assertEquals(LtiError.BAD_REQUEST, result.getError());
    Assert.assertEquals(Boolean.FALSE, result.getSuccess());
    Assert.assertEquals(null, result.getLtiLaunchResult());
}
 
Example #10
Source File: BasicLTIUtilTest.java    From basiclti-util-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateMessageFailOnValidateMessageIOException() throws Exception {

    SimpleOAuthValidator sov = Mockito.mock(SimpleOAuthValidator.class);
    PowerMockito.whenNew(SimpleOAuthValidator.class).withNoArguments().thenReturn(sov);
    Mockito.doThrow(new IOException("failed")).when(sov).validateMessage(Matchers.any(OAuthMessage.class), Matchers.any(OAuthAccessor.class));
    PowerMockito.mockStatic(OAuthSignatureMethod.class);
    PowerMockito.when(OAuthSignatureMethod.getBaseString(Matchers.any(OAuthMessage.class))).thenReturn("");

    LtiVerificationResult result = BasicLTIUtil.validateMessage(Mockito.mock(HttpServletRequest.class), "https://example.com/lti-launch", "secret");        

    Assert.assertEquals(LtiError.BAD_REQUEST, result.getError());
    Assert.assertEquals(Boolean.FALSE, result.getSuccess());
    Assert.assertEquals(null, result.getLtiLaunchResult());
}
 
Example #11
Source File: WaveService.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a URL that contains the necessary OAuth query parameters for the
 * given JSON string.
 *
 * The required OAuth parameters are:
 * <ul>
 * <li>oauth_body_hash</li>
 * <li>oauth_consumer_key</li>
 * <li>oauth_signature_method</li>
 * <li>oauth_timestamp</li>
 * <li>oauth_nonce</li>
 * <li>oauth_version</li>
 * <li>oauth_signature</li>
 * </ul>
 *
 * @param jsonBody the JSON string to construct the URL from.
 * @param rpcServerUrl the URL of the handler that services the JSON-RPC
 *        request.
 * @param accessor the OAuth accessor used to create the signed string.
 * @return a URL for the given JSON string, and the required OAuth parameters.
 */
public static String createOAuthUrlString(
    String jsonBody, String rpcServerUrl, OAuthAccessor accessor)
    throws IOException, URISyntaxException, OAuthException {
  OAuthMessage message =
      new OAuthMessage(POST, rpcServerUrl, Collections.<SimpleEntry<String, String>>emptyList());

  // Compute the hash of the body.
  byte[] rawBody = jsonBody.getBytes(UTF_8);
  byte[] hash = DigestUtils.sha(rawBody);
  byte[] encodedHash = Base64.encodeBase64(hash);
  message.addParameter(OAUTH_BODY_HASH, new String(encodedHash, UTF_8));

  // Add other parameters.

  message.addRequiredParameters(accessor);
  if (LOG.isLoggable(Level.FINE)) {
    LOG.fine("Signature base string: " + OAuthSignatureMethod.getBaseString(message));
  }

  // Construct the resulting URL.
  StringBuilder sb = new StringBuilder(rpcServerUrl);
  char connector = '?';
  for (Map.Entry<String, String> p : message.getParameters()) {
    if (!p.getKey().equals(jsonBody)) {
      sb.append(connector);
      sb.append(URLEncoder.encode(p.getKey(), UTF_8));
      sb.append('=');
      sb.append(URLEncoder.encode(p.getValue(), UTF_8));
      connector = '&';
    }
  }
  return sb.toString();
}
 
Example #12
Source File: SimpleOAuthValidator.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
protected void validateSignature(OAuthMessage message, OAuthAccessor accessor)
throws OAuthException, IOException, URISyntaxException {
    message.requireParameters(OAuth.OAUTH_CONSUMER_KEY,
            OAuth.OAUTH_SIGNATURE_METHOD, OAuth.OAUTH_SIGNATURE);
    OAuthSignatureMethod.newSigner(message, accessor).validate(message);
}
 
Example #13
Source File: SiteMembershipsSynchroniserImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private final void synchronizeMoodleExtSiteMemberships(final Site site, final String membershipsId, final String membershipsUrl, final String oauth_consumer_key, boolean isEmailTrustedConsumer) {

        // Lookup the secret
        final String configPrefix = "basiclti.provider." + oauth_consumer_key + ".";
        final String oauth_secret = serverConfigurationService.getString(configPrefix+ "secret", null);
        if (oauth_secret == null) {
            log.error("launch.key.notfound {}. This site's memberships will NOT be synchronised.", oauth_consumer_key);
            return;
        }

        String type = "readMembershipsWithGroups";
        String uuid = UUID.randomUUID().toString();
        String xml = "<sourcedId>" + membershipsId + "</sourcedId>";

        StringBuilder sb = new StringBuilder("<?xml version = \"1.0\" encoding = \"UTF-8\"?>");
        sb.append("<imsx_POXEnvelope xmlns = \"http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0\">");
        sb.append("<imsx_POXHeader>");
        sb.append("<imsx_POXRequestHeaderInfo>");
        sb.append("<imsx_version>V1.0</imsx_version>");
        sb.append("<imsx_messageIdentifier>" + uuid + "</imsx_messageIdentifier>");
        sb.append("</imsx_POXRequestHeaderInfo>");
        sb.append("</imsx_POXHeader>");
        sb.append("<imsx_POXBody>");
        sb.append("<" + type + "Request>");
        sb.append(xml);
        sb.append("</" + type + "Request>");
        sb.append("</imsx_POXBody>");
        sb.append("</imsx_POXEnvelope>");

        String callXml = sb.toString();

        if(log.isDebugEnabled()) log.debug("callXml: {}", callXml);

        String bodyHash = OAuthSignatureMethod.base64Encode(LegacyShaUtil.sha1(callXml));
        log.debug(bodyHash);

        OAuthMessage om = new OAuthMessage("POST", membershipsUrl, null);
        om.addParameter("oauth_body_hash", bodyHash);
        om.addParameter("oauth_consumer_key", oauth_consumer_key);
        om.addParameter("oauth_signature_method", "HMAC-SHA1");
        om.addParameter("oauth_version", "1.0");
        om.addParameter("oauth_timestamp", new Long(new Date().getTime()).toString());

        OAuthConsumer oc = new OAuthConsumer(null, oauth_consumer_key, oauth_secret, null);

        try {
            OAuthSignatureMethod osm = OAuthSignatureMethod.newMethod("HMAC-SHA1",new OAuthAccessor(oc));
            osm.sign(om);

            String authzHeader = om.getAuthorizationHeader(null);

            if(log.isDebugEnabled()) log.debug("AUTHZ HEADER: {}", authzHeader);

            URL url = new URL(membershipsUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setInstanceFollowRedirects(false); 
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", authzHeader);
            connection.setRequestProperty("Content-Length", "" + Integer.toString(callXml.getBytes().length));
            connection.setRequestProperty("Content-Type", "text/xml");
            connection.setUseCaches (false);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
            bw.write(callXml);
            bw.flush();
            bw.close();

            processMembershipsResponse(connection, site, oauth_consumer_key, isEmailTrustedConsumer);
        } catch (Exception e) {
            log.warn("Problem synchronizing Mooodle memberships.", e);
        }
    }
 
Example #14
Source File: SiteMembershipsSynchroniserImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private final void synchronizeLTI1SiteMemberships(final Site site, final String membershipsId, final String membershipsUrl, final String oauth_consumer_key, boolean isEmailTrustedConsumer) {

        // Lookup the secret
        final String configPrefix = "basiclti.provider." + oauth_consumer_key + ".";
        final String oauth_secret = serverConfigurationService.getString(configPrefix+ "secret", null);
        if (oauth_secret == null) {
            log.error("launch.key.notfound {}. This site's memberships will NOT be synchronised.", oauth_consumer_key);
            return;
        }

        OAuthMessage om = new OAuthMessage("POST", membershipsUrl, null);
        om.addParameter(OAuth.OAUTH_CONSUMER_KEY, oauth_consumer_key);
        om.addParameter(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1);
        om.addParameter(OAuth.OAUTH_VERSION, "1.0");
        om.addParameter(OAuth.OAUTH_TIMESTAMP, new Long((new Date().getTime()) / 1000).toString());
        om.addParameter(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());
        om.addParameter(BasicLTIConstants.LTI_MESSAGE_TYPE, "basic-lis-readmembershipsforcontext");
        om.addParameter(BasicLTIConstants.LTI_VERSION, "LTI-1p0");
        om.addParameter("id", membershipsId);

        OAuthConsumer oc = new OAuthConsumer(null, oauth_consumer_key, oauth_secret, null);

        try {
            OAuthSignatureMethod osm = OAuthSignatureMethod.newMethod(OAuth.HMAC_SHA1, new OAuthAccessor(oc));
            osm.sign(om);

            URL url = new URL(membershipsUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setInstanceFollowRedirects(false); 
            connection.setRequestMethod("POST");
            connection.setUseCaches (false);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
            bw.write(OAuth.formEncode(om.getParameters()));
            bw.flush();
            bw.close();

            processMembershipsResponse(connection, site, oauth_consumer_key, isEmailTrustedConsumer);
        } catch (Exception e) {
            log.warn("Problem synchronizing LTI1 memberships.", e);
        }
    }
 
Example #15
Source File: SiteMembershipsSynchroniserImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private final void synchronizeMoodleExtSiteMemberships(final Site site, final String membershipsId, final String membershipsUrl, final String oauth_consumer_key, boolean isEmailTrustedConsumer) {

        // Lookup the secret
        final String configPrefix = "basiclti.provider." + oauth_consumer_key + ".";
        final String oauth_secret = serverConfigurationService.getString(configPrefix+ "secret", null);
        if (oauth_secret == null) {
            log.error("launch.key.notfound {}. This site's memberships will NOT be synchronised.", oauth_consumer_key);
            return;
        }

        String type = "readMembershipsWithGroups";
        String uuid = UUID.randomUUID().toString();
        String xml = "<sourcedId>" + membershipsId + "</sourcedId>";

        StringBuilder sb = new StringBuilder("<?xml version = \"1.0\" encoding = \"UTF-8\"?>");
        sb.append("<imsx_POXEnvelope xmlns = \"http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0\">");
        sb.append("<imsx_POXHeader>");
        sb.append("<imsx_POXRequestHeaderInfo>");
        sb.append("<imsx_version>V1.0</imsx_version>");
        sb.append("<imsx_messageIdentifier>" + uuid + "</imsx_messageIdentifier>");
        sb.append("</imsx_POXRequestHeaderInfo>");
        sb.append("</imsx_POXHeader>");
        sb.append("<imsx_POXBody>");
        sb.append("<" + type + "Request>");
        sb.append(xml);
        sb.append("</" + type + "Request>");
        sb.append("</imsx_POXBody>");
        sb.append("</imsx_POXEnvelope>");

        String callXml = sb.toString();

        if(log.isDebugEnabled()) log.debug("callXml: {}", callXml);

        String bodyHash = OAuthSignatureMethod.base64Encode(LegacyShaUtil.sha1(callXml));
        log.debug(bodyHash);

        OAuthMessage om = new OAuthMessage("POST", membershipsUrl, null);
        om.addParameter("oauth_body_hash", bodyHash);
        om.addParameter("oauth_consumer_key", oauth_consumer_key);
        om.addParameter("oauth_signature_method", "HMAC-SHA1");
        om.addParameter("oauth_version", "1.0");
        om.addParameter("oauth_timestamp", new Long(new Date().getTime()).toString());

        OAuthConsumer oc = new OAuthConsumer(null, oauth_consumer_key, oauth_secret, null);

        try {
            OAuthSignatureMethod osm = OAuthSignatureMethod.newMethod("HMAC-SHA1",new OAuthAccessor(oc));
            osm.sign(om);

            String authzHeader = om.getAuthorizationHeader(null);

            if(log.isDebugEnabled()) log.debug("AUTHZ HEADER: {}", authzHeader);

            URL url = new URL(membershipsUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setInstanceFollowRedirects(false); 
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", authzHeader);
            connection.setRequestProperty("Content-Length", "" + Integer.toString(callXml.getBytes().length));
            connection.setRequestProperty("Content-Type", "text/xml");
            connection.setUseCaches (false);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
            bw.write(callXml);
            bw.flush();
            bw.close();

            processMembershipsResponse(connection, site, oauth_consumer_key, isEmailTrustedConsumer);
        } catch (Exception e) {
            log.warn("Problem synchronizing Mooodle memberships.", e);
        }
    }
 
Example #16
Source File: SiteMembershipsSynchroniserImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private final void synchronizeLTI1SiteMemberships(final Site site, final String membershipsId, final String membershipsUrl, final String oauth_consumer_key, boolean isEmailTrustedConsumer) {

        // Lookup the secret
        final String configPrefix = "basiclti.provider." + oauth_consumer_key + ".";
        final String oauth_secret = serverConfigurationService.getString(configPrefix+ "secret", null);
        if (oauth_secret == null) {
            log.error("launch.key.notfound {}. This site's memberships will NOT be synchronised.", oauth_consumer_key);
            return;
        }

        OAuthMessage om = new OAuthMessage("POST", membershipsUrl, null);
        om.addParameter(OAuth.OAUTH_CONSUMER_KEY, oauth_consumer_key);
        om.addParameter(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1);
        om.addParameter(OAuth.OAUTH_VERSION, "1.0");
        om.addParameter(OAuth.OAUTH_TIMESTAMP, new Long((new Date().getTime()) / 1000).toString());
        om.addParameter(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());
        om.addParameter(BasicLTIConstants.LTI_MESSAGE_TYPE, "basic-lis-readmembershipsforcontext");
        om.addParameter(BasicLTIConstants.LTI_VERSION, "LTI-1p0");
        om.addParameter("id", membershipsId);

        OAuthConsumer oc = new OAuthConsumer(null, oauth_consumer_key, oauth_secret, null);

        try {
            OAuthSignatureMethod osm = OAuthSignatureMethod.newMethod(OAuth.HMAC_SHA1, new OAuthAccessor(oc));
            osm.sign(om);

            URL url = new URL(membershipsUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setInstanceFollowRedirects(false); 
            connection.setRequestMethod("POST");
            connection.setUseCaches (false);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
            bw.write(OAuth.formEncode(om.getParameters()));
            bw.flush();
            bw.close();

            processMembershipsResponse(connection, site, oauth_consumer_key, isEmailTrustedConsumer);
        } catch (Exception e) {
            log.warn("Problem synchronizing LTI1 memberships.", e);
        }
    }
 
Example #17
Source File: SimpleOAuthValidator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected void validateSignature(OAuthMessage message, OAuthAccessor accessor)
throws OAuthException, IOException, URISyntaxException {
    message.requireParameters(OAuth.OAUTH_CONSUMER_KEY,
            OAuth.OAUTH_SIGNATURE_METHOD, OAuth.OAUTH_SIGNATURE);
    OAuthSignatureMethod.newSigner(message, accessor).validate(message);
}
 
Example #18
Source File: SimpleOAuthValidator.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
protected void validateSignature(OAuthMessage message, OAuthAccessor accessor)
throws OAuthException, IOException, URISyntaxException {
    message.requireParameters(OAuth.OAUTH_CONSUMER_KEY,
            OAuth.OAUTH_SIGNATURE_METHOD, OAuth.OAUTH_SIGNATURE);
    OAuthSignatureMethod.newSigner(message, accessor).validate(message);
}
 
Example #19
Source File: BasicLTIUtilTest.java    From basiclti-util-java with Apache License 2.0 3 votes vote down vote up
@Test
public void testValidateMessageFailWhenUriIsMalformed() throws Exception {
    
    HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class);
    String url = "https://example.com/lti-launch";
    
    PowerMockito.mockStatic(OAuthSignatureMethod.class);
    PowerMockito.when(OAuthSignatureMethod.getBaseString(Matchers.any(OAuthMessage.class))).thenThrow(new URISyntaxException("","",0));

    LtiVerificationResult result = BasicLTIUtil.validateMessage(requestMock, url, "secret");

    Assert.assertEquals(LtiError.BAD_REQUEST, result.getError());
    Assert.assertEquals(Boolean.FALSE, result.getSuccess());
    
}
 
Example #20
Source File: BasicLTIUtilTest.java    From basiclti-util-java with Apache License 2.0 3 votes vote down vote up
@Test
public void testValidateMessageFailOnIOException() throws Exception {
    
    HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class);
    String url = "https://example.com/lti-launch";
    
    PowerMockito.mockStatic(OAuthSignatureMethod.class);
    PowerMockito.when(OAuthSignatureMethod.getBaseString(Matchers.any(OAuthMessage.class))).thenThrow(new IOException(""));

    LtiVerificationResult result = BasicLTIUtil.validateMessage(requestMock, url, "secret");

    Assert.assertEquals(LtiError.BAD_REQUEST, result.getError());
    Assert.assertEquals(Boolean.FALSE, result.getSuccess());
    
}
 
Example #21
Source File: OAuthMessage.java    From sakai with Educational Community License v2.0 2 votes vote down vote up
/**
 * Add a signature to the message.
 * 
 * @throws URISyntaxException
 */
public void sign(OAuthAccessor accessor) throws IOException,
        OAuthException, URISyntaxException {
    OAuthSignatureMethod.newSigner(this, accessor).sign(this);
}
 
Example #22
Source File: OAuthMessage.java    From sakai with Educational Community License v2.0 2 votes vote down vote up
/**
 * Add a signature to the message.
 * 
 * @throws URISyntaxException
 */
public void sign(OAuthAccessor accessor) throws IOException,
        OAuthException, URISyntaxException {
    OAuthSignatureMethod.newSigner(this, accessor).sign(this);
}
 
Example #23
Source File: OAuthMessage.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Add a signature to the message.
 * 
 * @throws URISyntaxException
 */
public void sign(OAuthAccessor accessor) throws IOException,
        OAuthException, URISyntaxException {
    OAuthSignatureMethod.newSigner(this, accessor).sign(this);
}