net.oauth.OAuth Java Examples

The following examples show how to use net.oauth.OAuth. 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: HMAC_SHA256.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private byte[] computeSignature(String baseString)
        throws GeneralSecurityException, UnsupportedEncodingException {
    SecretKey key = null;
    synchronized (this) {
        if (this.key == null) {
            String keyString = OAuth.percentEncode(getConsumerSecret())
                    + '&' + OAuth.percentEncode(getTokenSecret());
            byte[] keyBytes = keyString.getBytes(ENCODING);
            this.key = new SecretKeySpec(keyBytes, MAC_NAME);
        }
        key = this.key;
    }
    Mac mac = Mac.getInstance(MAC_NAME);
    mac.init(key);
    byte[] text = baseString.getBytes(ENCODING);
    return mac.doFinal(text);
}
 
Example #2
Source File: DefaultOAuthStoreTest.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetConsumerKeyAndSecret() throws Exception {
    OAuthConsumerStore consumerStore = new OAuthConsumerStoreImpl();
    consumerStore.setGadgetUri(GADGET_URI);
    consumerStore.setConsumerKey("gadgetConsumer");
    consumerStore.setConsumerSecret(CONSUMER_SECRET);
    consumerStore.setKeyType(OAuthConsumerStore.KeyType.HMAC_SYMMETRIC);
    OAuthServiceProvider provider = new OAuthServiceProvider(null, null, null);

    expect(consumerStoreService.findByUriAndServiceName(GADGET_URI, SERVICE_NAME))
            .andReturn(consumerStore);
    replay(consumerStoreService);

    final OAuthStore.ConsumerInfo keyAndSecret =
            oAuthStore.getConsumerKeyAndSecret(token, SERVICE_NAME, provider);
    assertNotNull(keyAndSecret);
    assertEquals(OAuth.HMAC_SHA1, keyAndSecret.getConsumer().getProperty(
            OAuth.OAUTH_SIGNATURE_METHOD));

    verify(consumerStoreService);

}
 
Example #3
Source File: GoogleCallAction.java    From jivejdon with Apache License 2.0 6 votes vote down vote up
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
	String forwdUrl = mapping.findForward("success").getPath();
	String domainUrl = CallUtil.getCleanDomainUrl(request, forwdUrl);

	GoogleOAuthSubmitter googleOAuthSubmitter = (GoogleOAuthSubmitter) WebAppUtil.getComponentInstance("googleOAuthSubmitter", request);
	OAuthAccessor accessor = googleOAuthSubmitter.request(domainUrl);
	if (accessor.requestToken != null) {
		HttpSession session = request.getSession();
		session.setAttribute("resToken", accessor);
		Map<String, String> params = CallUtil.getParameters(request);
		session.setAttribute("subscriptionParameters", params);
		String authorizationURL = accessor.consumer.serviceProvider.userAuthorizationURL;
		authorizationURL = OAuth.addParameters(authorizationURL, OAuth.OAUTH_TOKEN, accessor.requestToken);
		response.sendRedirect(authorizationURL);
	} else {
		request.setAttribute("errors", "google authserver error");
	}

	return mapping.findForward("failure");
}
 
Example #4
Source File: TemporaryCredentialServiceTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTemporaryCredentialsURIQuery() throws Exception {
    Map<String, String> parameters = new HashMap<>();

    parameters.put(OAuth.OAUTH_SIGNATURE_METHOD, "HMAC-SHA1");
    parameters.put(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());
    parameters.put(OAuth.OAUTH_TIMESTAMP, String.valueOf(System.currentTimeMillis() / 1000));

    String uri = HOST + OAuthServer.PORT + TEMPORARY_CREDENTIALS_URL;
    WebClient wc = WebClient.create(uri);

    Token t = OAuthClientUtils.getRequestToken(wc,
        new OAuthClientUtils.Consumer(OAuthTestUtils.CLIENT_ID, OAuthTestUtils.CLIENT_SECRET),
                                     URI.create(OAuthTestUtils.CALLBACK),
                                     parameters);
    assertNotNull(t);
    assertNotNull(t.getToken());
    assertNotNull(t.getSecret());

}
 
Example #5
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 #6
Source File: OAuthClientUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static Token getRequestToken(WebClient requestTokenService,
                                    Consumer consumer,
                                    URI callback,
                                    Map<String, String> extraParams,
                                    Map<String, Object> oauthConsumerProps) throws OAuthServiceException {
    Map<String, String> parameters = new HashMap<>();
    if (extraParams != null) {
        parameters.putAll(extraParams);
    }
    parameters.put(OAuth.OAUTH_CALLBACK, callback.toString());

    if (oauthConsumerProps == null || !oauthConsumerProps.containsKey(OAuth.OAUTH_SIGNATURE_METHOD)) {
        parameters.put(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1);
    }
    parameters.put(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());
    parameters.put(OAuth.OAUTH_TIMESTAMP, String.valueOf(System.currentTimeMillis() / 1000));
    parameters.put(OAuth.OAUTH_CONSUMER_KEY, consumer.getKey());

    OAuthAccessor accessor = createAccessor(consumer, oauthConsumerProps);
    return getToken(requestTokenService, accessor, parameters);
}
 
Example #7
Source File: HMAC_SHA1.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private byte[] computeSignature(String baseString)
        throws GeneralSecurityException, UnsupportedEncodingException {
    SecretKey key = null;
    synchronized (this) {
        if (this.key == null) {
            String keyString = OAuth.percentEncode(getConsumerSecret())
                    + '&' + OAuth.percentEncode(getTokenSecret());
            byte[] keyBytes = keyString.getBytes(ENCODING);
            this.key = new SecretKeySpec(keyBytes, MAC_NAME);
        }
        key = this.key;
    }
    Mac mac = Mac.getInstance(MAC_NAME);
    mac.init(key);
    byte[] text = baseString.getBytes(ENCODING);
    return mac.doFinal(text);
}
 
Example #8
Source File: HMAC_SHA256.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private byte[] computeSignature(String baseString)
        throws GeneralSecurityException, UnsupportedEncodingException {
    SecretKey key = null;
    synchronized (this) {
        if (this.key == null) {
            String keyString = OAuth.percentEncode(getConsumerSecret())
                    + '&' + OAuth.percentEncode(getTokenSecret());
            byte[] keyBytes = keyString.getBytes(ENCODING);
            this.key = new SecretKeySpec(keyBytes, MAC_NAME);
        }
        key = this.key;
    }
    Mac mac = Mac.getInstance(MAC_NAME);
    mac.init(key);
    byte[] text = baseString.getBytes(ENCODING);
    return mac.doFinal(text);
}
 
Example #9
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 #10
Source File: Util.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public static OAuthAccessor convertToOAuthAccessor(Accessor accessor, OAuthConsumer oAuthConsumer)
        throws OAuthProblemException {
    if (accessor == null)
        return null;
    if (!oAuthConsumer.consumerKey.equals(accessor.getConsumerId()))
        throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_REFUSED);
    OAuthAccessor oAuthAccessor = new OAuthAccessor(oAuthConsumer);
    if (accessor.getType() == Accessor.Type.ACCESS)
        oAuthAccessor.accessToken = accessor.getToken();
    else
        oAuthAccessor.requestToken = accessor.getToken();
    oAuthAccessor.tokenSecret = accessor.getSecret();
    // Support Variable Accessor Secret http://wiki.oauth.net/w/page/12238502/AccessorSecret
    if (accessor.getAccessorSecret() != null)
        oAuthConsumer.setProperty(OAuthConsumer.ACCESSOR_SECRET, accessor.getAccessorSecret());
    return oAuthAccessor;
}
 
Example #11
Source File: DataApiOAuthServletTest.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
public void testDoAuthorizeTokenPostRejectsToken() throws Exception {
  when(req.getPathInfo()).thenReturn(AUTHORIZE_TOKEN_PATH);
  when(req.getMethod()).thenReturn("POST");
  when(req.getParameter("cancel")).thenReturn("yes");
  Map<String, String[]> params = getDoAuthorizeTokenParams();
  when(req.getParameterMap()).thenReturn(params);
  String token = servlet.getOrGenerateXsrfToken(ALEX);
  when(req.getParameter("token")).thenReturn(token);

  when(sessionManager.getLoggedInUser(any(HttpSession.class))).thenReturn(ALEX);

  servlet.doPost(req, resp);

  verify(resp).setStatus(HttpServletResponse.SC_OK);
  try {
    tokenContainer.getRequestTokenAccessor(params.get(OAuth.OAUTH_TOKEN)[0]);
    fail("This token should not be present anymore");
  } catch (OAuthProblemException e) {
    // expected
  }
}
 
Example #12
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 #13
Source File: OAuthSignatureMethod.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
protected static String normalizeParameters(
           Collection<? extends Map.Entry> parameters) throws IOException {
       if (parameters == null) {
           return "";
       }
       List<ComparableParameter> p = new ArrayList<ComparableParameter>(
               parameters.size());
       for (Map.Entry parameter : parameters) {
           if (!"oauth_signature".equals(parameter.getKey())) {
               p.add(new ComparableParameter(parameter));
           }
       }
       Collections.sort(p);
       return OAuth.formEncode(getParameters(p));
   }
 
Example #14
Source File: HMAC_SHA1.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private byte[] computeSignature(String baseString)
        throws GeneralSecurityException, UnsupportedEncodingException {
    SecretKey key = null;
    synchronized (this) {
        if (this.key == null) {
            String keyString = OAuth.percentEncode(getConsumerSecret())
                    + '&' + OAuth.percentEncode(getTokenSecret());
            byte[] keyBytes = keyString.getBytes(ENCODING);
            this.key = new SecretKeySpec(keyBytes, MAC_NAME);
        }
        key = this.key;
    }
    Mac mac = Mac.getInstance(MAC_NAME);
    mac.init(key);
    byte[] text = baseString.getBytes(ENCODING);
    return mac.doFinal(text);
}
 
Example #15
Source File: HMAC_SHA1.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private byte[] computeSignature(String baseString)
        throws GeneralSecurityException, UnsupportedEncodingException {
    SecretKey key = null;
    synchronized (this) {
        if (this.key == null) {
            String keyString = OAuth.percentEncode(getConsumerSecret())
                    + '&' + OAuth.percentEncode(getTokenSecret());
            byte[] keyBytes = keyString.getBytes(ENCODING);
            this.key = new SecretKeySpec(keyBytes, MAC_NAME);
        }
        key = this.key;
    }
    Mac mac = Mac.getInstance(MAC_NAME);
    mac.init(key);
    byte[] text = baseString.getBytes(ENCODING);
    return mac.doFinal(text);
}
 
Example #16
Source File: DataApiTokenContainer.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
/**
 * Authorizes a request token to be exchanged for an access token.
 *
 * @param requestToken the request token used for identification.
 * @param user the user that has authorized the token.
 * @throws OAuthProblemException if the request token does not map to an
 *         accessor or if the token was already used.
 */
public OAuthAccessor authorizeRequestToken(String requestToken, ParticipantId user)
    throws OAuthProblemException {
  Preconditions.checkNotNull(user, "User must not be null");

  OAuthAccessor accessor = getRequestTokenAccessor(requestToken);

  if (accessor.getProperty(USER_PROPERTY_NAME) != null) {
    throw OAuthUtil.newOAuthProblemException(OAuth.Problems.TOKEN_USED);
  }

  accessor.setProperty(USER_PROPERTY_NAME, user);
  requestTokenAccessors.put(requestToken, accessor);

  LOG.info("Authorized request token for " + user);
  return accessor.clone();
}
 
Example #17
Source File: DataApiTokenContainer.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
/**
 * Authorize the {@link OAuthAccessor} by generating a new access token and
 * token secret.
 *
 * @param requestToken the requestToken used for identifying the accessor that
 *        needs to be authorized.
 * @return a new {@link OAuthAccessor} with the access token and token secret
 *         set.
 * @throws OAuthProblemException if the request token in the accessor is not
 *         known.
 */
public OAuthAccessor generateAccessToken(String requestToken) throws OAuthProblemException {
  OAuthAccessor accessor = getRequestTokenAccessor(requestToken);

  if (accessor.getProperty(USER_PROPERTY_NAME) == null) {
    // User has not given the consumer permission yet.
    throw OAuthUtil.newOAuthProblemException(OAuth.Problems.PERMISSION_UNKNOWN);
  }

  // Token secret does not need to unique so can be generated now.
  accessor.tokenSecret = generateToken();

  do {
    accessor.accessToken = generateToken();
  } while (accessTokenAccessors.putIfAbsent(accessor.accessToken, accessor) != null);
  requestTokenAccessors.remove(accessor.requestToken);

  LOG.info("Generated access token for " + accessor.getProperty(USER_PROPERTY_NAME));
  return accessor.clone();
}
 
Example #18
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 #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: Util.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public static OAuthAccessor convertToOAuthAccessor(Accessor accessor, OAuthConsumer oAuthConsumer)
        throws OAuthProblemException {
    if (accessor == null)
        return null;
    if (!oAuthConsumer.consumerKey.equals(accessor.getConsumerId()))
        throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_REFUSED);
    OAuthAccessor oAuthAccessor = new OAuthAccessor(oAuthConsumer);
    if (accessor.getType() == Accessor.Type.ACCESS)
        oAuthAccessor.accessToken = accessor.getToken();
    else
        oAuthAccessor.requestToken = accessor.getToken();
    oAuthAccessor.tokenSecret = accessor.getSecret();
    // Support Variable Accessor Secret http://wiki.oauth.net/w/page/12238502/AccessorSecret
    if (accessor.getAccessorSecret() != null)
        oAuthConsumer.setProperty(OAuthConsumer.ACCESSOR_SECRET, accessor.getAccessorSecret());
    return oAuthAccessor;
}
 
Example #21
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 #22
Source File: DataApiTokenContainer.java    From swellrt with Apache License 2.0 6 votes vote down vote up
/**
 * Authorizes a request token to be exchanged for an access token.
 *
 * @param requestToken the request token used for identification.
 * @param user the user that has authorized the token.
 * @throws OAuthProblemException if the request token does not map to an
 *         accessor or if the token was already used.
 */
public OAuthAccessor authorizeRequestToken(String requestToken, ParticipantId user)
    throws OAuthProblemException {
  Preconditions.checkNotNull(user, "User must not be null");

  OAuthAccessor accessor = getRequestTokenAccessor(requestToken);

  if (accessor.getProperty(USER_PROPERTY_NAME) != null) {
    throw OAuthUtil.newOAuthProblemException(OAuth.Problems.TOKEN_USED);
  }

  accessor.setProperty(USER_PROPERTY_NAME, user);
  requestTokenAccessors.put(requestToken, accessor);

  LOG.info("Authorized request token for " + user);
  return accessor.clone();
}
 
Example #23
Source File: RequestTokenHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void validateCallbackURL(Client client,
                                   String oauthCallback) throws OAuthProblemException {
    // the callback must not be empty or null, and it should either match
    // the registered callback URI or have the common root with the
    // the registered application URI (but only if no callback was registered)
    if (!StringUtils.isEmpty(oauthCallback)) {
        boolean registeredCallbackIsEmpty = StringUtils.isEmpty(client.getCallbackURI());
        if (!registeredCallbackIsEmpty
            && oauthCallback.equals(client.getCallbackURI())) {
            return;
        }
        if (registeredCallbackIsEmpty
            && !StringUtils.isEmpty(client.getApplicationURI())
            && oauthCallback.startsWith(client.getApplicationURI())) {
            return;
        }

    }
    OAuthProblemException problemEx = new OAuthProblemException(
        OAuth.Problems.PARAMETER_REJECTED + " - " + OAuth.OAUTH_CALLBACK);
    problemEx
        .setParameter(OAuthProblemException.HTTP_STATUS_CODE,
            HttpServletResponse.SC_BAD_REQUEST);
    throw problemEx;
}
 
Example #24
Source File: DataApiTokenContainer.java    From swellrt with Apache License 2.0 6 votes vote down vote up
/**
 * Authorize the {@link OAuthAccessor} by generating a new access token and
 * token secret.
 *
 * @param requestToken the requestToken used for identifying the accessor that
 *        needs to be authorized.
 * @return a new {@link OAuthAccessor} with the access token and token secret
 *         set.
 * @throws OAuthProblemException if the request token in the accessor is not
 *         known.
 */
public OAuthAccessor generateAccessToken(String requestToken) throws OAuthProblemException {
  OAuthAccessor accessor = getRequestTokenAccessor(requestToken);

  if (accessor.getProperty(USER_PROPERTY_NAME) == null) {
    // User has not given the consumer permission yet.
    throw OAuthUtil.newOAuthProblemException(OAuth.Problems.PERMISSION_UNKNOWN);
  }

  // Token secret does not need to unique so can be generated now.
  accessor.tokenSecret = generateToken();

  do {
    accessor.accessToken = generateToken();
  } while (accessTokenAccessors.putIfAbsent(accessor.accessToken, accessor) != null);
  requestTokenAccessors.remove(accessor.requestToken);

  LOG.info("Generated access token for " + accessor.getProperty(USER_PROPERTY_NAME));
  return accessor.clone();
}
 
Example #25
Source File: DataApiServlet.java    From swellrt 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 #26
Source File: OAuthClientUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static Token getAccessToken(WebClient accessTokenService,
                                   Consumer consumer,
                                   Token requestToken,
                                   String verifier,
                                   Map<String, Object> oauthConsumerProps) throws OAuthServiceException {
    Map<String, String> parameters = new HashMap<>();
    parameters.put(OAuth.OAUTH_CONSUMER_KEY, consumer.getKey());
    parameters.put(OAuth.OAUTH_TOKEN, requestToken.getToken());
    parameters.put(OAuth.OAUTH_VERIFIER, verifier);
    if (oauthConsumerProps == null || !oauthConsumerProps.containsKey(OAuth.OAUTH_SIGNATURE_METHOD)) {
        parameters.put(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1);
    }

    OAuthAccessor accessor = createAccessor(consumer, oauthConsumerProps);
    accessor.requestToken = requestToken.getToken();
    accessor.tokenSecret = requestToken.getSecret();
    return getToken(accessTokenService, accessor, parameters);
}
 
Example #27
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 #28
Source File: OAuthClientUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static String createAuthorizationHeader(Consumer consumer,
                                               Token accessToken,
                                               String method,
                                               String requestURI,
                                               Map<String, Object> oauthConsumerProps) {
    Map<String, String> parameters = new HashMap<>();
    parameters.put(OAuth.OAUTH_CONSUMER_KEY, consumer.getKey());
    if (accessToken != null) {
        parameters.put(OAuth.OAUTH_TOKEN, accessToken.getToken());
    }
    if (oauthConsumerProps == null || !oauthConsumerProps.containsKey(OAuth.OAUTH_SIGNATURE_METHOD)) {
        parameters.put(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1);
    }
    parameters.put(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());
    parameters.put(OAuth.OAUTH_TIMESTAMP, String.valueOf(System.currentTimeMillis() / 1000));

    OAuthAccessor accessor = createAccessor(consumer, oauthConsumerProps);
    if (accessToken != null) {
        accessor.accessToken = accessToken.getToken();
        accessor.tokenSecret = accessToken.getSecret();
    }
    return doGetAuthorizationHeader(accessor, method, requestURI, parameters);
}
 
Example #29
Source File: DataApiOAuthServletTest.java    From swellrt with Apache License 2.0 6 votes vote down vote up
public void testDoAuthorizeTokenPostRejectsToken() throws Exception {
  when(req.getPathInfo()).thenReturn(AUTHORIZE_TOKEN_PATH);
  when(req.getMethod()).thenReturn("POST");
  when(req.getParameter("cancel")).thenReturn("yes");
  Map<String, String[]> params = getDoAuthorizeTokenParams();
  when(req.getParameterMap()).thenReturn(params);
  String token = servlet.getOrGenerateXsrfToken(ALEX);
  when(req.getParameter("token")).thenReturn(token);

  when(sessionManager.getLoggedInUser(any(HttpSession.class))).thenReturn(ALEX);

  servlet.doPost(req, resp);

  verify(resp).setStatus(HttpServletResponse.SC_OK);
  try {
    tokenContainer.getRequestTokenAccessor(params.get(OAuth.OAUTH_TOKEN)[0]);
    fail("This token should not be present anymore");
  } catch (OAuthProblemException e) {
    // expected
  }
}
 
Example #30
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));
}