Java Code Examples for net.oauth.OAuthMessage#requireParameters()

The following examples show how to use net.oauth.OAuthMessage#requireParameters() . 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: 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 2
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 3
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 4
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 5
Source File: CallbackURLController.java    From cxf with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/callback")
protected ModelAndView handleRequest(@ModelAttribute("oAuthParams") OAuthParams oAuthParams,
                                     HttpServletRequest request) throws Exception {

    OAuthMessage message = OAuthServlet.getMessage(request, request.getRequestURL().toString());

    try {
        message.requireParameters(OAuth.OAUTH_TOKEN, OAuth.OAUTH_VERIFIER);
        oAuthParams.setOauthToken(message.getToken());
        oAuthParams.setOauthVerifier(message.getParameter(OAuth.OAUTH_VERIFIER));

        oAuthParams.setClientID(Common.findCookieValue(request, "clientID"));
        oAuthParams.setClientSecret(Common.findCookieValue(request, "clientSecret"));
    } catch (OAuthProblemException e) {
        oAuthParams.setErrorMessage("OAuth problem: " + e.getProblem() + e.getParameters().toString());
    }


    return new ModelAndView("tokenRequest");
}
 
Example 6
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 7
Source File: OAuthSignatureMethod.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static OAuthSignatureMethod newSigner(OAuthMessage message,
        OAuthAccessor accessor) throws IOException, OAuthException {
    message.requireParameters(OAuth.OAUTH_SIGNATURE_METHOD);
    OAuthSignatureMethod signer = newMethod(message.getSignatureMethod(),
            accessor);
    signer.setTokenSecret(accessor.tokenSecret);
    return signer;
}
 
Example 8
Source File: OAuthClient.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/** Get a fresh request token from the service provider.
    * 
    * @param accessor
    *            should contain a consumer that contains a non-null consumerKey
    *            and consumerSecret. Also,
    *            accessor.consumer.serviceProvider.requestTokenURL should be
    *            the URL (determined by the service provider) for getting a
    *            request 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 void getRequestToken(OAuthAccessor accessor, String httpMethod,
           Collection<? extends Map.Entry> parameters) throws IOException,
           OAuthException, URISyntaxException {
       accessor.accessToken = null;
       accessor.tokenSecret = null;
       {
           // This code supports the 'Variable Accessor Secret' extension
           // described in http://oauth.pbwiki.com/AccessorSecret
           Object accessorSecret = accessor
                   .getProperty(OAuthConsumer.ACCESSOR_SECRET);
           if (accessorSecret != null) {
               List<Map.Entry> p = (parameters == null) ? new ArrayList<Map.Entry>(
                       1)
                       : new ArrayList<Map.Entry>(parameters);
               p.add(new OAuth.Parameter("oauth_accessor_secret",
                       accessorSecret.toString()));
               parameters = p;
               // But don't modify the caller's parameters.
           }
       }
       OAuthMessage response = invoke(accessor, httpMethod,
               accessor.consumer.serviceProvider.requestTokenURL, parameters);
       accessor.requestToken = response.getParameter(OAuth.OAUTH_TOKEN);
       accessor.tokenSecret = response.getParameter(OAuth.OAUTH_TOKEN_SECRET);
       response.requireParameters(OAuth.OAUTH_TOKEN, OAuth.OAUTH_TOKEN_SECRET);
   }
 
Example 9
Source File: OAuthSignatureMethod.java    From sakai with Educational Community License v2.0 5 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);
       String otherBaseString = null;

// Allow for some confusion coming through load balancers
if ( baseString.startsWith(POST_HTTP) ) { 
	otherBaseString = baseString.replaceFirst("^"+POST_HTTP,POST_SECURE);
} else if ( baseString.startsWith(POST_SECURE) ) { 
	otherBaseString = baseString.replaceFirst("^"+POST_SECURE, POST_HTTP);
} else if ( baseString.startsWith(GET_HTTP) ) { 
	otherBaseString = baseString.replaceFirst("^"+GET_HTTP,GET_SECURE);
} else if ( baseString.startsWith(GET_SECURE) ) { 
	otherBaseString = baseString.replaceFirst("^"+GET_SECURE, GET_HTTP);
}

boolean valid = isValid(signature, baseString);
if ( ! valid && otherBaseString != null ) valid = isValid(signature, otherBaseString);

       if (!valid) {
           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 10
Source File: OAuthSignatureMethod.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static OAuthSignatureMethod newSigner(OAuthMessage message,
        OAuthAccessor accessor) throws IOException, OAuthException {
    message.requireParameters(OAuth.OAUTH_SIGNATURE_METHOD);
    OAuthSignatureMethod signer = newMethod(message.getSignatureMethod(),
            accessor);
    signer.setTokenSecret(accessor.tokenSecret);
    return signer;
}
 
Example 11
Source File: OAuthClient.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/** Get a fresh request token from the service provider.
    * 
    * @param accessor
    *            should contain a consumer that contains a non-null consumerKey
    *            and consumerSecret. Also,
    *            accessor.consumer.serviceProvider.requestTokenURL should be
    *            the URL (determined by the service provider) for getting a
    *            request 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 void getRequestToken(OAuthAccessor accessor, String httpMethod,
           Collection<? extends Map.Entry> parameters) throws IOException,
           OAuthException, URISyntaxException {
       accessor.accessToken = null;
       accessor.tokenSecret = null;
       {
           // This code supports the 'Variable Accessor Secret' extension
           // described in http://oauth.pbwiki.com/AccessorSecret
           Object accessorSecret = accessor
                   .getProperty(OAuthConsumer.ACCESSOR_SECRET);
           if (accessorSecret != null) {
               List<Map.Entry> p = (parameters == null) ? new ArrayList<Map.Entry>(
                       1)
                       : new ArrayList<Map.Entry>(parameters);
               p.add(new OAuth.Parameter("oauth_accessor_secret",
                       accessorSecret.toString()));
               parameters = p;
               // But don't modify the caller's parameters.
           }
       }
       OAuthMessage response = invoke(accessor, httpMethod,
               accessor.consumer.serviceProvider.requestTokenURL, parameters);
       accessor.requestToken = response.getParameter(OAuth.OAUTH_TOKEN);
       accessor.tokenSecret = response.getParameter(OAuth.OAUTH_TOKEN_SECRET);
       response.requireParameters(OAuth.OAUTH_TOKEN, OAuth.OAUTH_TOKEN_SECRET);
   }
 
Example 12
Source File: OAuthSignatureMethod.java    From sakai with Educational Community License v2.0 5 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);
       String otherBaseString = null;

// Allow for some confusion coming through load balancers
if ( baseString.startsWith(POST_HTTP) ) { 
	otherBaseString = baseString.replaceFirst("^"+POST_HTTP,POST_SECURE);
} else if ( baseString.startsWith(POST_SECURE) ) { 
	otherBaseString = baseString.replaceFirst("^"+POST_SECURE, POST_HTTP);
} else if ( baseString.startsWith(GET_HTTP) ) { 
	otherBaseString = baseString.replaceFirst("^"+GET_HTTP,GET_SECURE);
} else if ( baseString.startsWith(GET_SECURE) ) { 
	otherBaseString = baseString.replaceFirst("^"+GET_SECURE, GET_HTTP);
}

boolean valid = isValid(signature, baseString);
if ( ! valid && otherBaseString != null ) valid = isValid(signature, otherBaseString);

       if (!valid) {
           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 13
Source File: OAuthSignatureMethod.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static OAuthSignatureMethod newSigner(OAuthMessage message,
        OAuthAccessor accessor) throws IOException, OAuthException {
    message.requireParameters(OAuth.OAUTH_SIGNATURE_METHOD);
    OAuthSignatureMethod signer = newMethod(message.getSignatureMethod(),
            accessor);
    signer.setTokenSecret(accessor.tokenSecret);
    return signer;
}
 
Example 14
Source File: OAuthUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static OAuthMessage getOAuthMessage(MessageContext mc,
                                           HttpServletRequest request,
                                           String[] requiredParams) throws Exception {
    OAuthMessage oAuthMessage = OAuthServlet.getMessage(request, request.getRequestURL().toString());
    OAuthUtils.addParametersIfNeeded(mc, request, oAuthMessage);
    oAuthMessage.requireParameters(requiredParams);
    return oAuthMessage;
}
 
Example 15
Source File: AbstractAuthFilter.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticates the third-party consumer and returns
 * {@link OAuthInfo} bean capturing the information about the request.
 * @param req http request
 * @return OAuth info
 * @see OAuthInfo
 * @throws Exception
 * @throws OAuthProblemException
 */
protected OAuthInfo handleOAuthRequest(HttpServletRequest req) throws
    Exception, OAuthProblemException {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.log(Level.FINE, "OAuth security filter for url: {0}", req.getRequestURL());
    }

    AccessToken accessToken = null;
    Client client = null;

    OAuthMessage oAuthMessage = OAuthServlet.getMessage(new CustomHttpServletWrapper(req),
                                                        OAuthServlet.getRequestURL(req));
    if (oAuthMessage.getParameter(OAuth.OAUTH_TOKEN) != null) {
        oAuthMessage.requireParameters(REQUIRED_PARAMETERS);

        accessToken = dataProvider.getAccessToken(oAuthMessage.getToken());

        //check if access token is not null
        if (accessToken == null) {
            LOG.warning("Access token is unavailable");
            throw new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
        }
        client = accessToken.getClient();

        OAuthUtils.validateMessage(oAuthMessage, client, accessToken,
                                   dataProvider, validator);
    } else {
        String consumerKey = null;
        String consumerSecret = null;

        String authHeader = oAuthMessage.getHeader("Authorization");
        if (authHeader != null) {
            if (authHeader.startsWith("OAuth")) {
                consumerKey = oAuthMessage.getParameter(OAuth.OAUTH_CONSUMER_KEY);
                consumerSecret = oAuthMessage.getParameter(OAuthConstants.OAUTH_CONSUMER_SECRET);
            } else if (authHeader.startsWith("Basic")) {
                AuthorizationPolicy policy = getAuthorizationPolicy(authHeader);
                if (policy != null) {
                    consumerKey = policy.getUserName();
                    consumerSecret = policy.getPassword();
                }
            }
        }

        if (consumerKey != null) {
            client = dataProvider.getClient(consumerKey);
        }
        if (client == null) {
            LOG.warning("Client is invalid");
            throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN);
        }

        if (consumerSecret != null && !consumerSecret.equals(client.getSecretKey())) {
            LOG.warning("Client secret is invalid");
            throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN);
        }
        OAuthUtils.validateMessage(oAuthMessage, client, null,
                                   dataProvider, validator);
        accessToken = client.getPreAuthorizedToken();
        if (accessToken == null || !accessToken.isPreAuthorized()) {
            LOG.warning("Preauthorized access token is unavailable");
            throw new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
        }
    }

    List<OAuthPermission> permissions = accessToken.getScopes();
    List<OAuthPermission> matchingPermissions = new ArrayList<>();

    for (OAuthPermission perm : permissions) {
        boolean uriOK = checkRequestURI(req, perm.getUris());
        boolean verbOK = checkHttpVerb(req, perm.getHttpVerbs());
        if (uriOK && verbOK) {
            matchingPermissions.add(perm);
        }
    }

    if (!permissions.isEmpty() && matchingPermissions.isEmpty()) {
        String message = "Client has no valid permissions";
        LOG.warning(message);
        throw new OAuthProblemException(message);
    }
    return new OAuthInfo(accessToken, matchingPermissions);

}