net.oauth.OAuthMessage Java Examples

The following examples show how to use net.oauth.OAuthMessage. 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: BasicLTIUtilTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Test
public void validateGoodMessage() {
	Map<String, String> paramMap = new HashMap<>();

	String url = "https://www.sakailms.org/";
	String secret = "shhh";
	String key = "zuul";

	Map<String, String> signedParams_pre = BasicLTIUtil.signProperties(paramMap, url, OAuthMessage.POST, key, secret,
			"guid", "desc", "tool_url",
			"name", "email", null);

	//Need to convert from a <String, String> to a <String, String[]> so I can mock the HttpServletRequest
	Map<String, String[]> signedParams = signedParams_pre.entrySet()
			.stream()
			.collect(Collectors.toMap(Map.Entry::getKey,
					e -> new String[]{e.getValue()}));

	HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
	Mockito.when(req.getParameterMap()).thenReturn(signedParams);
	Mockito.when(req.getMethod()).thenReturn(OAuthMessage.POST);

	Object obj = BasicLTIUtil.validateMessage(req, url, secret, key);
	assertEquals(Boolean.TRUE, obj);
}
 
Example #2
Source File: HttpRequestMessage.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static List<OAuth.Parameter> getParameters(HttpServletRequest request) {
       List<OAuth.Parameter> list = new ArrayList<OAuth.Parameter>();
       for (Enumeration<String> headers = request.getHeaders("Authorization"); headers != null
               && headers.hasMoreElements();) {
           String header = headers.nextElement();
           for (OAuth.Parameter parameter : OAuthMessage
                   .decodeAuthorization(header)) {
               if (!"realm".equalsIgnoreCase(parameter.getKey())) {
                   list.add(parameter);
               }
           }
       }
       for (Object e : request.getParameterMap().entrySet()) {
           Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) e;
           String name = entry.getKey();
           for (String value : entry.getValue()) {
               list.add(new OAuth.Parameter(name, value));
           }
       }
       return list;
   }
 
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: DataApiOAuthServletTest.java    From swellrt with Apache License 2.0 6 votes vote down vote up
public void testDoRequestToken() throws Exception {
  when(req.getPathInfo()).thenReturn(REQUEST_TOKEN_PATH);
  when(req.getMethod()).thenReturn("GET");

  servlet.doGet(req, resp);

  verify(resp).setStatus(HttpServletResponse.SC_OK);
  verify(validator).validateMessage(any(OAuthMessage.class), any(OAuthAccessor.class));
  assertTrue(outputStream.isClosed());

  // Verify that the output contains a token and token secret.
  String output = outputStream.toString();
  Map<String, String> parameters = toMap(OAuth.decodeForm(output));
  assertTrue("Request token should be present", parameters.containsKey(OAuth.OAUTH_TOKEN));
  assertTrue(
      "Request token secret should be present", parameters.containsKey(OAuth.OAUTH_TOKEN_SECRET));
  OAuthAccessor requestTokenAccessor =
      tokenContainer.getRequestTokenAccessor(parameters.get(OAuth.OAUTH_TOKEN));
  assertNotNull("Container should have stored the token", requestTokenAccessor);
  assertEquals("Correct secret should be returned", requestTokenAccessor.tokenSecret,
      parameters.get(OAuth.OAUTH_TOKEN_SECRET));
}
 
Example #5
Source File: BasicLTIUtilTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Test
public void validateGoodMessage() {
	Map<String, String> paramMap = new HashMap<>();

	String url = "https://www.sakailms.org/";
	String secret = "shhh";
	String key = "zuul";

	Map<String, String> signedParams_pre = BasicLTIUtil.signProperties(paramMap, url, OAuthMessage.POST, key, secret,
			"guid", "desc", "tool_url",
			"name", "email", null);

	//Need to convert from a <String, String> to a <String, String[]> so I can mock the HttpServletRequest
	Map<String, String[]> signedParams = signedParams_pre.entrySet()
			.stream()
			.collect(Collectors.toMap(Map.Entry::getKey,
					e -> new String[]{e.getValue()}));

	HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
	Mockito.when(req.getParameterMap()).thenReturn(signedParams);
	Mockito.when(req.getMethod()).thenReturn(OAuthMessage.POST);

	Object obj = BasicLTIUtil.validateMessage(req, url, secret, key);
	assertEquals(Boolean.TRUE, obj);
}
 
Example #6
Source File: BasicLTIUtilTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Test
public void checkProperties() {
	Map<String, String> props = new HashMap<>();
	boolean checkedProperties = BasicLTIUtil.checkProperties(props, "https://www.sakailms.org/", "POST",
			"key", "secret");
	assertFalse(checkedProperties);

	String url = "https://www.sakailms.org/";
	String key = "key";
	String secret = "secret";
	Map<String, String> signedParams = BasicLTIUtil.signProperties(props, url, OAuthMessage.POST, key, secret,
			"guid", "desc", "tool_url",
			"name", "email", null);
	checkedProperties = BasicLTIUtil.checkProperties(signedParams, url, OAuthMessage.POST,
			key, secret);
	assertTrue(checkedProperties);
}
 
Example #7
Source File: LtiOauthSigner.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Map<String, String> signParameters(Map<String, String> parameters, String key, String secret, String url, String method) throws LtiSigningException {
    OAuthMessage oam = new OAuthMessage(method, url, parameters.entrySet());
    OAuthConsumer cons = new OAuthConsumer(null, key, secret, null);
    OAuthAccessor acc = new OAuthAccessor(cons);
    try {
        oam.addRequiredParameters(acc);

        Map<String, String> signedParameters = new HashMap<>();
        for(Map.Entry<String, String> param : oam.getParameters()){
            signedParameters.put(param.getKey(), param.getValue());
        }
        return signedParameters;
    } catch (OAuthException |IOException |URISyntaxException e) {
        throw new LtiSigningException("Error signing LTI request.", e);
    }
}
 
Example #8
Source File: BasicLTIUtilTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Test
public void signProperties() {
	Map<String, String> props = new HashMap<>();
	Map<String, String> extra = new HashMap<>();

	String url = "https://www.sakailms.org/";
	String key = "key";
	String secret = "secret";
	Map<String, String> signedParams = BasicLTIUtil.signProperties(props, url, OAuthMessage.POST, key, secret,
			"guid", "desc", "tool_url",
			"name", "email", extra);
	assertNotNull(signedParams);

	signedParams = BasicLTIUtil.signProperties(props, url, OAuthMessage.GET, null, secret,
			"guid", "desc", "tool_url",
			"name", "email", extra);
	assertNotNull(signedParams);
}
 
Example #9
Source File: OAuthSignatureMethod.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static String getBaseString(OAuthMessage message)
        throws IOException, URISyntaxException {
    List<Map.Entry<String, String>> parameters;
    String url = message.URL;
    int q = url.indexOf('?');
    if (q < 0) {
        parameters = message.getParameters();
    } else {
        // Combine the URL query string with the other parameters:
        parameters = new ArrayList<Map.Entry<String, String>>();
        parameters.addAll(OAuth.decodeForm(message.URL.substring(q + 1)));
        parameters.addAll(message.getParameters());
        url = url.substring(0, q);
    }
    return OAuth.percentEncode(message.method.toUpperCase()) + '&'
            + OAuth.percentEncode(normalizeUrl(url)) + '&'
            + OAuth.percentEncode(normalizeParameters(parameters));
}
 
Example #10
Source File: OAuthSignatureMethod.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check whether the message has a valid signature.
 * @throws URISyntaxException 
 *
 * @throws OAuthProblemException
 *             the signature is invalid
 */
public void validate(OAuthMessage message)
throws IOException, OAuthException, URISyntaxException {
    message.requireParameters("oauth_signature");
    String signature = message.getSignature();
    String baseString = getBaseString(message);
    if (!isValid(signature, baseString)) {

 // *LAMS* added by LAMS
 log.debug("Error. Signature invalid. oauth_signature=" + signature + ", oauth_signature_base_string="
  + baseString + ", oauth_signature_method=" + message.getSignatureMethod());
     		
        OAuthProblemException problem = new OAuthProblemException(
                "signature_invalid");
        problem.setParameter("oauth_signature", signature);
        problem.setParameter("oauth_signature_base_string", baseString);
        problem.setParameter("oauth_signature_method", message
                .getSignatureMethod());
        throw problem;
    }
}
 
Example #11
Source File: OAuthClientUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static String doGetAuthorizationHeader(OAuthAccessor accessor,
        String method, String requestURI, Map<String, String> parameters) {
    try {
        OAuthMessage msg = accessor.newRequestMessage(method, requestURI, parameters.entrySet());
        StringBuilder sb = new StringBuilder();
        sb.append(msg.getAuthorizationHeader(null));
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            if (!entry.getKey().startsWith("oauth_")) {
                sb.append(", ");
                sb.append(OAuth.percentEncode(entry.getKey())).append("=\"");
                sb.append(OAuth.percentEncode(entry.getValue())).append('"');
            }
        }
        return sb.toString();
    } catch (Exception ex) {
        throw new ProcessingException(ex);
    }
}
 
Example #12
Source File: DataApiOAuthServletTest.java    From swellrt with Apache License 2.0 6 votes vote down vote up
public void testDoExchangeToken() throws Exception {
  when(req.getPathInfo()).thenReturn(ACCESS_TOKEN_PATH);
  when(req.getMethod()).thenReturn("GET");
  Map<String, String[]> params = getDoExchangeTokenParams();
  when(req.getParameterMap()).thenReturn(params);

  servlet.doGet(req, resp);

  verify(validator).validateMessage(any(OAuthMessage.class), any(OAuthAccessor.class));
  verify(resp).setStatus(HttpServletResponse.SC_OK);

  // Verify that the output contains a token and token secret.
  String output = outputStream.toString();
  Map<String, String> parameters = toMap(OAuth.decodeForm(output));
  assertTrue("Access token should be present", parameters.containsKey(OAuth.OAUTH_TOKEN));
  assertTrue(
      "Access token secret should be present", parameters.containsKey(OAuth.OAUTH_TOKEN_SECRET));
  OAuthAccessor accessTokenAccessor =
      tokenContainer.getAccessTokenAccessor(parameters.get(OAuth.OAUTH_TOKEN));
  assertNotNull("Container should have stored the token", accessTokenAccessor);
  assertEquals("Correct secret should be returned", accessTokenAccessor.tokenSecret,
      parameters.get(OAuth.OAUTH_TOKEN_SECRET));
}
 
Example #13
Source File: HttpRequestMessage.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static List<OAuth.Parameter> getParameters(HttpServletRequest request) {
    List<OAuth.Parameter> list = new ArrayList<OAuth.Parameter>();
    for (Enumeration<String> headers = request.getHeaders("Authorization"); headers != null
            && headers.hasMoreElements();) {
        String header = headers.nextElement();
        for (OAuth.Parameter parameter : OAuthMessage
                .decodeAuthorization(header)) {
            if (!"realm".equalsIgnoreCase(parameter.getKey())) {
                list.add(parameter);
            }
        }
    }
    for (Object e : request.getParameterMap().entrySet()) {
        Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) e;
        String name = entry.getKey();
        for (String value : entry.getValue()) {
            list.add(new OAuth.Parameter(name, value));
        }
    }
    return list;
}
 
Example #14
Source File: DataApiServletTest.java    From swellrt with Apache License 2.0 6 votes vote down vote up
public void testDoPostExecutesAndWritesResponse() throws Exception {
  String operationId = "op1";
  OperationRequest operation = new OperationRequest("wavelet.create", operationId);
  List<OperationRequest> operations = Collections.singletonList(operation);
  when(robotSerializer.deserializeOperations(anyString())).thenReturn(operations);
  String responseValue = "response value";
  when(robotSerializer.serialize(any(), any(Type.class), any(ProtocolVersion.class))).thenReturn(
      responseValue);
  Map<String, String[]> params = getOAuthParams();
  when(req.getParameterMap()).thenReturn(params);

  OperationService service = mock(OperationService.class);
  when(operationRegistry.getServiceFor(any(OperationType.class))).thenReturn(service);

  servlet.doPost(req, resp);

  verify(validator).validateMessage(any(OAuthMessage.class), any(OAuthAccessor.class));
  verify(operationRegistry).getServiceFor(any(OperationType.class));
  verify(service).execute(eq(operation), any(OperationContext.class), eq(ALEX));
  verify(resp).setStatus(HttpServletResponse.SC_OK);
  assertEquals("Response should have been written into the servlet", responseValue,
      stringWriter.toString());
}
 
Example #15
Source File: DataApiServletTest.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
public void testDoPostExecutesAndWritesResponse() throws Exception {
  String operationId = "op1";
  OperationRequest operation = new OperationRequest("wavelet.create", operationId);
  List<OperationRequest> operations = Collections.singletonList(operation);
  when(robotSerializer.deserializeOperations(any())).thenReturn(operations);
  String responseValue = "response value";
  when(robotSerializer.serialize(any(), any(Type.class), any(ProtocolVersion.class))).thenReturn(
      responseValue);
  Map<String, String[]> params = getOAuthParams();
  when(req.getParameterMap()).thenReturn(params);

  OperationService service = mock(OperationService.class);
  when(operationRegistry.getServiceFor(any(OperationType.class))).thenReturn(service);

  servlet.doPost(req, resp);

  verify(validator).validateMessage(any(OAuthMessage.class), any(OAuthAccessor.class));
  verify(operationRegistry).getServiceFor(any(OperationType.class));
  verify(service).execute(eq(operation), any(OperationContext.class), eq(ALEX));
  verify(resp).setStatus(HttpServletResponse.SC_OK);
  assertEquals("Response should have been written into the servlet", responseValue,
      stringWriter.toString());
}
 
Example #16
Source File: LtiOauthSigner.java    From basiclti-util-java with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> signParameters(Map<String, String> parameters, String key, String secret, String url, String method) throws LtiSigningException {
    OAuthMessage oam = new OAuthMessage(method, url, parameters.entrySet());
    OAuthConsumer cons = new OAuthConsumer(null, key, secret, null);
    OAuthAccessor acc = new OAuthAccessor(cons);
    try {
        oam.addRequiredParameters(acc);

        Map<String, String> signedParameters = new HashMap<>();
        for(Map.Entry<String, String> param : oam.getParameters()){
            signedParameters.put(param.getKey(), param.getValue());
        }
        return signedParameters;
    } catch (OAuthException |IOException |URISyntaxException e) {
        throw new LtiSigningException("Error signing LTI request.", e);
    }
}
 
Example #17
Source File: DataApiServlet.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
/**
 * Entry point for the Data API Calls.
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  OAuthMessage message = new HttpRequestMessage(req, req.getRequestURL().toString());

  OAuthAccessor accessor;
  try {
    message.requireParameters(OAuth.OAUTH_TOKEN);
    accessor = tokenContainer.getAccessTokenAccessor(message.getParameter(OAuth.OAUTH_TOKEN));
  } catch (OAuthProblemException e) {
    LOG.info("No valid OAuth token present", e);
    // Have to set status here manually, cannot use e.getHttpStatusCode
    // because message.requireParameters doesn't set it in the exception.
    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
    return;
  }
  ParticipantId participant =
      (ParticipantId) accessor.getProperty(DataApiTokenContainer.USER_PROPERTY_NAME);
  
  processOpsRequest(req, resp, message, accessor, participant);
}
 
Example #18
Source File: OAuthClient.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
    * Get an access token from the service provider, in exchange for an
    * authorized request token.
    * 
    * @param accessor
    *            should contain a non-null requestToken and tokenSecret, and a
    *            consumer that contains a consumerKey and consumerSecret. Also,
    *            accessor.consumer.serviceProvider.accessTokenURL should be the
    *            URL (determined by the service provider) for getting an access
    *            token.
    * @param httpMethod
    *            typically OAuthMessage.POST or OAuthMessage.GET, or null to
    *            use the default method.
    * @param parameters
    *            additional parameters for this request, or null to indicate
    *            that there are no additional parameters.
    * @throws OAuthProblemException
    *             the HTTP response status code was not 200 (OK)
    */
   @SuppressWarnings("rawtypes")
public OAuthMessage getAccessToken(OAuthAccessor accessor, String httpMethod,
           Collection<? extends Map.Entry> parameters) throws IOException, OAuthException, URISyntaxException {
       if (accessor.requestToken != null) {
           if (parameters == null) {
               parameters = OAuth.newList(OAuth.OAUTH_TOKEN, accessor.requestToken);
           } else if (!OAuth.newMap(parameters).containsKey(OAuth.OAUTH_TOKEN)) {
               List<Map.Entry> p = new ArrayList<Map.Entry>(parameters);
               p.add(new OAuth.Parameter(OAuth.OAUTH_TOKEN, accessor.requestToken));
               parameters = p;
           }
       }
       OAuthMessage response = invoke(accessor, httpMethod,
               accessor.consumer.serviceProvider.accessTokenURL, parameters);
       response.requireParameters(OAuth.OAUTH_TOKEN, OAuth.OAUTH_TOKEN_SECRET);
       accessor.accessToken = response.getParameter(OAuth.OAUTH_TOKEN);
       accessor.tokenSecret = response.getParameter(OAuth.OAUTH_TOKEN_SECRET);
       return response;
   }
 
Example #19
Source File: DataApiOAuthServletTest.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
public void testDoRequestToken() throws Exception {
  when(req.getPathInfo()).thenReturn(REQUEST_TOKEN_PATH);
  when(req.getMethod()).thenReturn("GET");

  servlet.doGet(req, resp);

  verify(resp).setStatus(HttpServletResponse.SC_OK);
  verify(validator).validateMessage(any(OAuthMessage.class), any(OAuthAccessor.class));
  assertTrue(outputStream.isClosed());

  // Verify that the output contains a token and token secret.
  String output = outputStream.toString();
  Map<String, String> parameters = toMap(OAuth.decodeForm(output));
  assertTrue("Request token should be present", parameters.containsKey(OAuth.OAUTH_TOKEN));
  assertTrue(
      "Request token secret should be present", parameters.containsKey(OAuth.OAUTH_TOKEN_SECRET));
  OAuthAccessor requestTokenAccessor =
      tokenContainer.getRequestTokenAccessor(parameters.get(OAuth.OAUTH_TOKEN));
  assertNotNull("Container should have stored the token", requestTokenAccessor);
  assertEquals("Correct secret should be returned", requestTokenAccessor.tokenSecret,
      parameters.get(OAuth.OAUTH_TOKEN_SECRET));
}
 
Example #20
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 #21
Source File: OAuthSignatureMethod.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public static String getBaseString(OAuthMessage message)
        throws IOException, URISyntaxException {
    List<Map.Entry<String, String>> parameters;
    String url = message.URL;
    int q = url.indexOf('?');
    if (q < 0) {
        parameters = message.getParameters();
    } else {
        // Combine the URL query string with the other parameters:
        parameters = new ArrayList<Map.Entry<String, String>>();
        parameters.addAll(OAuth.decodeForm(message.URL.substring(q + 1)));
        parameters.addAll(message.getParameters());
        url = url.substring(0, q);
    }
    return OAuth.percentEncode(message.method.toUpperCase()) + '&'
            + OAuth.percentEncode(normalizeUrl(url)) + '&'
            + OAuth.percentEncode(normalizeParameters(parameters));
}
 
Example #22
Source File: OAuthSignatureMethod.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public static String getBaseString(OAuthMessage message)
        throws IOException, URISyntaxException {
    List<Map.Entry<String, String>> parameters;
    String url = message.URL;
    int q = url.indexOf('?');
    if (q < 0) {
        parameters = message.getParameters();
    } else {
        // Combine the URL query string with the other parameters:
        parameters = new ArrayList<Map.Entry<String, String>>();
        parameters.addAll(OAuth.decodeForm(message.URL.substring(q + 1)));
        parameters.addAll(message.getParameters());
        url = url.substring(0, q);
    }
    return OAuth.percentEncode(message.method.toUpperCase()) + '&'
            + OAuth.percentEncode(normalizeUrl(url)) + '&'
            + OAuth.percentEncode(normalizeParameters(parameters));
}
 
Example #23
Source File: BasicLTIUtilTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Test
public void signProperties() {
	Map<String, String> props = new HashMap<>();
	Map<String, String> extra = new HashMap<>();

	String url = "https://www.sakailms.org/";
	String key = "key";
	String secret = "secret";
	Map<String, String> signedParams = BasicLTIUtil.signProperties(props, url, OAuthMessage.POST, key, secret,
			"guid", "desc", "tool_url",
			"name", "email", extra);
	assertNotNull(signedParams);

	signedParams = BasicLTIUtil.signProperties(props, url, OAuthMessage.GET, null, secret,
			"guid", "desc", "tool_url",
			"name", "email", extra);
	assertNotNull(signedParams);
}
 
Example #24
Source File: HttpRequestMessage.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static List<OAuth.Parameter> getParameters(HttpServletRequest request) {
       List<OAuth.Parameter> list = new ArrayList<OAuth.Parameter>();
       for (Enumeration<String> headers = request.getHeaders("Authorization"); headers != null
               && headers.hasMoreElements();) {
           String header = headers.nextElement();
           for (OAuth.Parameter parameter : OAuthMessage
                   .decodeAuthorization(header)) {
               if (!"realm".equalsIgnoreCase(parameter.getKey())) {
                   list.add(parameter);
               }
           }
       }
       for (Object e : request.getParameterMap().entrySet()) {
           Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) e;
           String name = entry.getKey();
           for (String value : entry.getValue()) {
               list.add(new OAuth.Parameter(name, value));
           }
       }
       return list;
   }
 
Example #25
Source File: BasicLTIUtilTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Test
public void checkProperties() {
	Map<String, String> props = new HashMap<>();
	boolean checkedProperties = BasicLTIUtil.checkProperties(props, "https://www.sakailms.org/", "POST",
			"key", "secret");
	assertFalse(checkedProperties);

	String url = "https://www.sakailms.org/";
	String key = "key";
	String secret = "secret";
	Map<String, String> signedParams = BasicLTIUtil.signProperties(props, url, OAuthMessage.POST, key, secret,
			"guid", "desc", "tool_url",
			"name", "email", null);
	checkedProperties = BasicLTIUtil.checkProperties(signedParams, url, OAuthMessage.POST,
			key, secret);
	assertTrue(checkedProperties);
}
 
Example #26
Source File: OAuthClient.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
    * Get an access token from the service provider, in exchange for an
    * authorized request token.
    * 
    * @param accessor
    *            should contain a non-null requestToken and tokenSecret, and a
    *            consumer that contains a consumerKey and consumerSecret. Also,
    *            accessor.consumer.serviceProvider.accessTokenURL should be the
    *            URL (determined by the service provider) for getting an access
    *            token.
    * @param httpMethod
    *            typically OAuthMessage.POST or OAuthMessage.GET, or null to
    *            use the default method.
    * @param parameters
    *            additional parameters for this request, or null to indicate
    *            that there are no additional parameters.
    * @throws OAuthProblemException
    *             the HTTP response status code was not 200 (OK)
    */
   @SuppressWarnings("rawtypes")
public OAuthMessage getAccessToken(OAuthAccessor accessor, String httpMethod,
           Collection<? extends Map.Entry> parameters) throws IOException, OAuthException, URISyntaxException {
       if (accessor.requestToken != null) {
           if (parameters == null) {
               parameters = OAuth.newList(OAuth.OAUTH_TOKEN, accessor.requestToken);
           } else if (!OAuth.newMap(parameters).containsKey(OAuth.OAUTH_TOKEN)) {
               List<Map.Entry> p = new ArrayList<Map.Entry>(parameters);
               p.add(new OAuth.Parameter(OAuth.OAUTH_TOKEN, accessor.requestToken));
               parameters = p;
           }
       }
       OAuthMessage response = invoke(accessor, httpMethod,
               accessor.consumer.serviceProvider.accessTokenURL, parameters);
       response.requireParameters(OAuth.OAUTH_TOKEN, OAuth.OAUTH_TOKEN_SECRET);
       accessor.accessToken = response.getParameter(OAuth.OAUTH_TOKEN);
       accessor.tokenSecret = response.getParameter(OAuth.OAUTH_TOKEN_SECRET);
       return response;
   }
 
Example #27
Source File: DataApiOAuthServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testDoExchangeTokenUnauthorizedOnURISyntaxException() throws Exception {
  when(req.getPathInfo()).thenReturn(ACCESS_TOKEN_PATH);
  when(req.getMethod()).thenReturn("GET");
  Map<String, String[]> params = getDoExchangeTokenParams();
  when(req.getParameterMap()).thenReturn(params);

  doThrow(new URISyntaxException("", "")).when(validator).validateMessage(
      any(OAuthMessage.class), any(OAuthAccessor.class));

  servlet.doGet(req, resp);

  verify(validator).validateMessage(any(OAuthMessage.class), any(OAuthAccessor.class));
  verify(resp).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #28
Source File: DataApiOAuthServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testDoExchangeTokenUnauthorizedOnOAuthException() throws Exception {
  when(req.getPathInfo()).thenReturn(ACCESS_TOKEN_PATH);
  when(req.getMethod()).thenReturn("GET");

  Map<String, String[]> params = getDoExchangeTokenParams();
  when(req.getParameterMap()).thenReturn(params);

  doThrow(new OAuthException("")).when(validator).validateMessage(
      any(OAuthMessage.class), any(OAuthAccessor.class));

  servlet.doGet(req, resp);

  verify(validator).validateMessage(any(OAuthMessage.class), any(OAuthAccessor.class));
  verify(resp).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #29
Source File: DataApiOAuthServletTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
public void testDoRequestTokenUnauthorizedOnOAuthException() throws Exception {
  when(req.getPathInfo()).thenReturn(REQUEST_TOKEN_PATH);
  when(req.getMethod()).thenReturn("GET");

  doThrow(new OAuthException("")).when(validator).validateMessage(
      any(OAuthMessage.class), any(OAuthAccessor.class));

  servlet.doGet(req, resp);

  verify(resp).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #30
Source File: OAuthClient.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
    * Construct a request message, send it to the service provider and get the
    * response.
    * 
    * @param httpMethod
    *            the HTTP request method, or null to use the default method
    * @return the response
    * @throws URISyntaxException
    *             the given url isn't valid syntactically
    * @throws OAuthProblemException
    *             the HTTP response status code was not 200 (OK)
    */
   @SuppressWarnings("rawtypes")
public OAuthMessage invoke(OAuthAccessor accessor, String httpMethod,
           String url, Collection<? extends Map.Entry> parameters)
   throws IOException, OAuthException, URISyntaxException {
       OAuthMessage request = accessor.newRequestMessage(httpMethod, url, parameters);
       Object accepted = accessor.consumer.getProperty(OAuthConsumer.ACCEPT_ENCODING);
       if (accepted != null) {
           request.getHeaders().add(new OAuth.Parameter(HttpMessage.ACCEPT_ENCODING, accepted.toString()));
       }
       Object ps = accessor.consumer.getProperty(PARAMETER_STYLE);
       net.oauth.ParameterStyle style = (ps == null) ? net.oauth.ParameterStyle.BODY
               : Enum.valueOf(net.oauth.ParameterStyle.class, ps.toString());
       return invoke(request, style);
   }