Java源码示例:net.oauth.OAuthAccessor
示例1
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");
}
示例2
@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);
}
}
示例3
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);
}
示例4
protected void initialize(String name, OAuthAccessor accessor)
throws OAuthException {
String secret = accessor.consumer.consumerSecret;
if (name.endsWith(_ACCESSOR)) {
// This code supports the 'Accessor Secret' extensions
// described in http://oauth.pbwiki.com/AccessorSecret
final String key = OAuthConsumer.ACCESSOR_SECRET;
Object accessorSecret = accessor.getProperty(key);
if (accessorSecret == null) {
accessorSecret = accessor.consumer.getProperty(key);
}
if (accessorSecret != null) {
secret = accessorSecret.toString();
}
}
if (secret == null) {
secret = "";
}
setConsumerSecret(secret);
}
示例5
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;
}
示例6
/**
* 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();
}
示例7
/**
* 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();
}
示例8
/**
* 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);
}
示例9
/**
* Constructor.
*
* @param consumerKey the consumer key.
* @param consumerSecret the consumer secret
* @param rpcServerUrl the URL of the JSON-RPC request handler
*/
public ConsumerData(String consumerKey, String consumerSecret, String rpcServerUrl) {
String consumerKeyPrefix = "";
// NOTE(ljvderijk): Present for backwards capability.
if (RPC_URL.equals(rpcServerUrl) || SANDBOX_RPC_URL.equals(rpcServerUrl)) {
consumerKeyPrefix = "google.com:";
}
this.consumerKey = consumerKeyPrefix + consumerKey;
this.consumerSecret = consumerSecret;
this.rpcServerUrl = rpcServerUrl;
userAuthenticated = false;
OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, null);
consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1);
accessor = new OAuthAccessor(consumer);
}
示例10
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());
}
示例11
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));
}
示例12
@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);
}
}
示例13
/**
* 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();
}
示例14
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);
}
示例15
protected void initialize(String name, OAuthAccessor accessor)
throws OAuthException {
String secret = accessor.consumer.consumerSecret;
if (name.endsWith(_ACCESSOR)) {
// This code supports the 'Accessor Secret' extensions
// described in http://oauth.pbwiki.com/AccessorSecret
final String key = OAuthConsumer.ACCESSOR_SECRET;
Object accessorSecret = accessor.getProperty(key);
if (accessorSecret == null) {
accessorSecret = accessor.consumer.getProperty(key);
}
if (accessorSecret != null) {
secret = accessorSecret.toString();
}
}
if (secret == null) {
secret = "";
}
setConsumerSecret(secret);
}
示例16
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;
}
示例17
/**
* Tests the case when the user has not started the authorization process (no
* request token).
*/
public final void testCheckAuthorizationNoRequestToken() {
// Setup.
LoginFormHandler loginForm = mock(LoginFormHandler.class);
OAuthClient client = mock(OAuthClient.class);
PersistenceManager pm = mock(PersistenceManager.class);
PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class);
OAuthAccessor accessor = buildAccessor(CONSUMER_KEY, CONSUMER_SECRET,
REQUEST_TOKEN_URL, AUTHORIZE_URL, CALLBACK_URL, ACCESS_TOKEN_URL);
accessor.requestToken = REQUEST_TOKEN_STRING;
oauthService = new OAuthServiceImpl(accessor, client, pmf,
USER_RECORD_KEY);
OAuthUser userWithRequestToken = new OAuthUser(USER_RECORD_KEY, REQUEST_TOKEN_STRING);
// Expectations.
when(pmf.getPersistenceManager()).thenReturn(pm);
when(pm.getObjectById(OAuthUser.class, USER_RECORD_KEY)).thenReturn(null, userWithRequestToken,
userWithRequestToken);
assertFalse(oauthService.checkAuthorization(null, loginForm));
String authUrl = userWithRequestToken.getAuthUrl();
try {
new URL(authUrl);
} catch (MalformedURLException e) {
fail("Malformed authUrl");
}
assertTrue(Pattern.matches(".+(oauth_token){1}.+", authUrl));
assertTrue(Pattern.matches(".+(oauth_callback){1}.+", authUrl));
}
示例18
public OAuthAccessor request(String backUrl) {
OAuthConsumer consumer = new OAuthConsumer(backUrl, goolgeOAuthParamVO.CONSUMER_KEY, goolgeOAuthParamVO.CONSUMER_SECRET,
goolgeOAuthParamVO.oAuthServiceProvider);
OAuthAccessor accessor = new OAuthAccessor(consumer);
try {
List<OAuth.Parameter> parameters = OAuth.newList(OAuth.OAUTH_CALLBACK, backUrl);
parameters.add(new OAuth.Parameter("scope", goolgeOAuthParamVO.scope));
CLIENT.getRequestTokenResponse(accessor, null, parameters);
} catch (Exception e) {
logger.error("request error:" + e);
}
return accessor;
}
示例19
public void testGenerateAccessToken() throws Exception {
OAuthAccessor unauthorizedRequestToken = container.generateRequestToken(consumer);
OAuthAccessor authorizedRequestToken =
container.authorizeRequestToken(unauthorizedRequestToken.requestToken, ALEX);
OAuthAccessor accessToken = container.generateAccessToken(authorizedRequestToken.requestToken);
assertEquals("Consumer should be retained", consumer, accessToken.consumer);
assertFalse("Access token should be generated", accessToken.accessToken.isEmpty());
assertFalse("Token secret should be generated", accessToken.tokenSecret.isEmpty());
assertTrue("Accessor should be in storage",
areEqual(accessToken, container.getAccessTokenAccessor(accessToken.accessToken)));
}
示例20
public OAuthUserVO getUserInfo(OAuthAccessor accessor) throws Exception {
OAuthUserVO weiboUser = null;
InputStream in = null;
try {
accessor.consumer.setProperty(OAUTH_SIGNATURE_METHOD, HMAC_SHA1);
OAuthMessage message = accessor.newRequestMessage(OAuthMessage.GET, goolgeOAuthParamVO.userInfo, null);
OAuthMessage result = CLIENT.invoke(message, ParameterStyle.AUTHORIZATION_HEADER);
in = result.getBodyAsStream();
String jsonStr = getString(new InputStreamReader(in, Charset.forName("UTF-8")));
JSONObject json = new JSONObject(jsonStr);
String id = json.getString("id");
String atName = json.getString("name");
String description = json.getString("name");
String url = "";
if (!UtilValidate.isEmpty(json.getString("link")))
url = json.getString("link");// t.qq.com/name
String profileurl = "";
if (!UtilValidate.isEmpty(json.getString("picture")))
profileurl = json.getString("picture");
weiboUser = new OAuthUserVO(id, atName, description, url, profileurl);
} catch (Exception e) {
throw new Exception(e);
} finally {
if (in != null)
in.close();
}
return weiboUser;
}
示例21
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
String verifier = request.getParameter("oauth_verifier");
if (verifier != null) {
OAuthAccessor resToken = (OAuthAccessor) session.getAttribute("resToken");
if (resToken != null) {
GoogleOAuthSubmitter googleOAuthSubmitter = (GoogleOAuthSubmitter) WebAppUtil.getComponentInstance("googleOAuthSubmitter", request);
OAuthAccessor accessToken = googleOAuthSubmitter.requstAccessToken(resToken, verifier);
if (accessToken.accessToken == null)
return mapping.findForward("failure");
OAuthAccountService oAuthAccountService = (OAuthAccountService) WebAppUtil.getService("oAuthAccountService", request);
Account account = oAuthAccountService.saveGoogle(accessToken);
Map<String, String> subParams = (Map<String, String>) session.getAttribute("subscriptionParameters");
if (subParams != null && account != null) {
String forwdUrl = mapping.findForward("success").getPath();
subParams.put("j_username", account.getUsername());
subParams.put("j_password", oAuthAccountService.createPassword(accessToken.accessToken));
subParams.put("rememberMe", "true");
String domainUrl = CallUtil.getDomainUrl(request, forwdUrl, subParams);
response.sendRedirect(domainUrl);
}
}
}
return mapping.findForward("failure");
}
示例22
public void testDoRequestTokenUnauthorizedOnURISyntaxException() throws Exception {
when(req.getPathInfo()).thenReturn(REQUEST_TOKEN_PATH);
when(req.getMethod()).thenReturn("GET");
doThrow(new URISyntaxException("", "")).when(validator).validateMessage(
any(OAuthMessage.class), any(OAuthAccessor.class));
servlet.doGet(req, resp);
verify(resp).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
示例23
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;
}
示例24
/**
* 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();
}
示例25
/** 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);
}
示例26
/**
* 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);
}
示例27
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;
}
示例28
/**
* Performs 3-legged OAuth authorization through Data API.
*
* @param service wave service.
*/
public String threeLeggedOAuth(WaveService service) throws IOException {
Console.println("Paste this URL in your browser:\n" + serverUrl + GET_ALL_TOKENS_URL_POSTFIX);
Console.println("Type the code you received here: ");
String authorizationCode = new String(
Base64.decodeBase64(Console.readLine().getBytes("UTF-8")), "UTF-8");
StringTokenizer st = new StringTokenizer(authorizationCode);
String requestToken = st.nextToken();
String accessToken = st.nextToken();
String tokenSecret = st.nextToken();
String requestUrl = serverUrl + REQUEST_URL_POSTFIX;
String authUrl = serverUrl + AUTH_URL_POSTFIX;
String accessUrl = serverUrl + ACCESS_URL_POSTFIX;
OAuthServiceProvider provider = new OAuthServiceProvider(requestUrl
+ "?scope=" + URLEncoder.encode("", "utf-8"), authUrl, accessUrl);
OAuthConsumer consumer = new OAuthConsumer("", THREE_LEGGED_API_CONSUMER_KEY,
THREE_LEGGED_API_CONSUMER_SECRET, provider);
OAuthAccessor accessor = new OAuthAccessor(consumer);
accessor.requestToken = requestToken;
accessor.accessToken = accessToken;
accessor.tokenSecret = tokenSecret;
String rpcServerUrl = serverUrl + DATA_API_RPC_URL_POSTFIX;
service.setupOAuth(accessor, rpcServerUrl);
return rpcServerUrl;
}
示例29
@Inject
@VisibleForTesting
DataApiTokenContainer(TokenGenerator tokenGenerator) {
this.tokenGenerator = tokenGenerator;
requestTokenAccessors =
CacheBuilder.newBuilder().expireAfterWrite(REQUEST_TOKEN_EXPIRATION, TimeUnit.MINUTES)
.<String, OAuthAccessor>build().asMap();
accessTokenAccessors =
CacheBuilder.newBuilder().expireAfterWrite(ACCESS_TOKEN_EXPIRATION, TimeUnit.MINUTES)
.<String, OAuthAccessor>build().asMap();
}
示例30
/**
* Gets the {@link OAuthAccessor} that is identified by the given request
* token. Any changes made to the accessor's fields, except the consumer, will
* not be reflected in this container.
*
* @param requestToken the request token used for identification.
* @throws OAuthProblemException if the token does not map to an accessor.
*/
public OAuthAccessor getRequestTokenAccessor(String requestToken) throws OAuthProblemException {
OAuthAccessor accessor = requestTokenAccessors.get(requestToken);
if (accessor == null) {
OAuthProblemException exception =
OAuthUtil.newOAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
exception.setParameter(OAuth.OAUTH_TOKEN, requestToken);
throw exception;
}
return accessor.clone();
}