/** * Lookup information contained in the gadget spec. */ private OAuthServiceProvider lookupSpecInfo(ISecurityToken securityToken, OAuthArguments arguments, AccessorInfoBuilder accessorBuilder, OAuthResponseParams responseParams) { GadgetSpec spec = findSpec(securityToken, arguments, responseParams); OAuthSpec oauthSpec = spec.getModulePrefs().getOAuthSpec(); if (oauthSpec == null) { throw responseParams.oauthRequestException(OAuthError.BAD_OAUTH_CONFIGURATION, "Failed to retrieve OAuth URLs, spec for gadget " + securityToken.getAppUrl() + " does not contain OAuth element."); } OAuthService service = oauthSpec.getServices()[arguments.getServiceName()]; if (service == null) { throw responseParams.oauthRequestException(OAuthError.BAD_OAUTH_CONFIGURATION, "Failed to retrieve OAuth URLs, spec for gadget does not contain OAuth service " + arguments.getServiceName() + ". Known services: " + String.Join(",", oauthSpec.getServices().Keys.AsEnumerable().ToArray()) + '.'); } // In theory some one could specify different parameter locations for request token and // access token requests, but that's probably not useful. We just use the request token // rules for everything. accessorBuilder.setParameterLocation(getStoreLocation(service.getRequestUrl().location, responseParams)); accessorBuilder.setMethod(getStoreMethod(service.getRequestUrl().method, responseParams)); OAuthServiceProvider provider = new OAuthServiceProvider( service.getRequestUrl().url.ToString(), service.getAuthorizationUrl().ToString(), service.getAccessUrl().url.ToString()); return(provider); }
/** * Create response parameters. */ public OAuthResponseParams(ISecurityToken securityToken, sRequest originalRequest, BlobCrypter stateCrypter) { this.securityToken = securityToken; this.originalRequest = originalRequest; newClientState = new OAuthClientState(stateCrypter); }
public override void removeToken(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName) { ++accessTokenRemoveCount; BasicOAuthStoreTokenIndex tokenKey = MakeBasicOAuthStoreTokenIndex(securityToken, serviceName, tokenName); tokens.Remove(tokenKey); }
public override ConsumerInfo getConsumerKeyAndSecret(ISecurityToken securityToken, String serviceName, OAuthServiceProvider provider) { ++consumerKeyLookupCount; BasicOAuthStoreConsumerIndex pk = new BasicOAuthStoreConsumerIndex(); pk.setGadgetUri(securityToken.getAppUrl()); pk.setServiceName(serviceName); BasicOAuthStoreConsumerKeyAndSecret cks = consumerInfos.ContainsKey(pk) ? consumerInfos[pk] : defaultKey; if (cks == null) { throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, "No key for gadget " + securityToken.getAppUrl() + " and service " + serviceName); } OAuthConsumer consumer; if (cks.keyType == BasicOAuthStoreConsumerKeyAndSecret.KeyType.RSA_PRIVATE) { consumer = new OAuthConsumer(null, cks.ConsumerKey, null, provider); consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.RSA_SHA1); consumer.setProperty(RSA_SHA1.X509_CERTIFICATE, cks.CertName); consumer.setProperty(RSA_SHA1.X509_CERTIFICATE_PASS, cks.CertPass); } else { consumer = new OAuthConsumer(null, cks.ConsumerKey, cks.ConsumerSecret, provider); consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1); } return(new ConsumerInfo(consumer, cks.ConsumerKey)); }
public RestfulRequestItem(HttpRequest request, ISecurityToken token, BeanConverter converter) : base(GetServiceFromPath(request.RawUrl), GetMethod(request), token, converter) { url = request.RawUrl.Replace(SOCIAL_RESTFUL_PATH, "/"); parameters = CreateParameterMap(request); try { using (Stream istream = request.InputStream) { MemoryStream memoryStream = new MemoryStream(0x10000); byte[] buffer = new byte[0x1000]; int bytes; while ((bytes = istream.Read(buffer, 0, buffer.Length)) > 0) { memoryStream.Write(buffer, 0, bytes); } postData = request.ContentEncoding.GetString(memoryStream.ToArray()); } } catch (IOException e) { throw new Exception("Could not get the post data from the request", e); } }
public RestfulRequestItem(String path, String method, String postData, ISecurityToken token, BeanConverter converter) : base(GetServiceFromPath(path), method, token, converter) { this.postData = postData; url = path; PutUrlParamsIntoParameters(); }
public void deletePersonData(UserId uid, GroupId groupId, String appId, HashSet <String> fields, ISecurityToken token) { var ids = GetIdSet(uid, groupId, token); if (ids.Count < 1) { throw new ProtocolException(ResponseError.BAD_REQUEST, "No _userId specified"); } if (ids.Count > 1) { throw new ProtocolException(ResponseError.BAD_REQUEST, "Multiple _userIds not supported"); } IEnumerator <string> iuserid = ids.GetEnumerator(); iuserid.MoveNext(); string userId = iuserid.Current; #if AZURE using (var db = new AzureDbFetcher()) #else using (var db = new RayaDbFetcher()) #endif { if (!db.DeleteAppData(userId, fields, appId)) { throw new ProtocolException(ResponseError.INTERNAL_ERROR, "Internal server error"); } } }
public async Task <IEnumerable <T> > ReadAsync <T>( CancellationToken cancellationToken, ISecurityToken securityToken, ITimeOutPolicy policy, string content, string route, Encoding encoding) { var request = CreateRequest(route, Actions.Read, content, HttpVerb.Get, encoding); var result = await Exchanger.GetString( cancellationToken, securityToken, policy, request).ConfigureAwait(false); try { return(Deserialize <T>(result)); } catch (JsonSerializationException exception) { LogSerializationException(exception, request, result); throw; } }
public RequestItem(String service, String operation, ISecurityToken token, BeanConverter converter) { this.service = service; this.operation = operation; this.token = token; this.converter = converter; }
/// <summary> /// Executes the action filter against the provided filter context /// </summary> /// <param name="filterContext">The filter context to execture against</param> public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext is null) { throw new ArgumentNullException(nameof(filterContext)); } if (filterContext.HttpContext.Request.Cookies["X-Session"] != null) { try { ISecurityToken token = filterContext.HttpContext.RequestServices.GetService <ISecurityToken>(); if (token != null && token.IsValid) { base.OnActionExecuting(filterContext); } } catch (Exception) { throw new SecurityException(MISSING_SECURITY_TOKEN_MESSAGE); } } else { throw new SecurityException(MISSING_SECURITY_TOKEN_MESSAGE); } }
public void deleteActivities(UserId userId, GroupId groupId, String appId, HashSet <String> activityIds, ISecurityToken token) { try { String user = userId.getUserId(token); if (db.getJSONObject(ACTIVITIES_TABLE).Contains(user)) { JsonArray activities = db.getJSONObject(ACTIVITIES_TABLE)[user] as JsonArray; if (activities != null) { JsonArray newList = new JsonArray(); for (int i = 0; i < activities.Length; i++) { JsonObject activity = activities[i] as JsonObject; if (activity != null && !activityIds.Contains(activity[Activity.Field.ID.ToDescriptionString()] as string)) { newList.Put(activity); } } db.getJSONObject(ACTIVITIES_TABLE).Put(user, newList); // TODO. This seems very odd that we return no useful response in this case // There is no way to represent not-found // if (found) { ?? //} } } // What is the appropriate response here?? } catch (Exception je) { throw new ProtocolException(ResponseError.INTERNAL_ERROR, je.Message); } }
protected void dispatchBatch(JsonArray batch, HttpResponse response, ISecurityToken token) { // Use linked hash map to preserve order List <IAsyncResult> responses = new List <IAsyncResult>(batch.Length); // Gather all Futures. We do this up front so that // the first call to get() comes after all futures are created, // which allows for implementations that batch multiple Futures // into single requests. for (int i = 0; i < batch.Length; i++) { JsonObject batchObj = batch.GetObject(i); RpcRequestItem requestItem = new RpcRequestItem(batchObj, token, jsonConverter); responses.Add(HandleRequestItem(requestItem)); } // Resolve each Future into a response. // TODO: should use shared deadline across each request List <Object> result = new List <object>(); for (int i = 0; i < batch.Length; i++) { JsonObject batchObj = batch.GetObject(i); String key = null; if (batchObj.Contains("id")) { key = batchObj["id"] as String; } result.Add(getJsonResponse(key, getResponseItem(responses[i]), null)); } response.Output.Write(jsonConverter.ConvertToString(result)); }
/** * Format a response as JSON, including additional JSON inserted by * chained content fetchers. */ private String convertResponseToJson(ISecurityToken authToken, HttpRequestWrapper request, sResponse results) { try { String originalUrl = request.getParameter(URL_PARAM); String body = results.responseString; if ("FEED".Equals(request.getParameter(CONTENT_TYPE_PARAM))) { body = processFeed(originalUrl, request, body); } JsonObject resp = FetchResponseUtils.getResponseAsJson(results, body); if (authToken != null) { String updatedAuthToken = authToken.getUpdatedToken(); if (updatedAuthToken != null) { resp.Put("st", updatedAuthToken); } } // Use raw param as key as URL may have to be decoded return(new JsonObject().Put(originalUrl, resp).ToString()); } catch (JsonException) { return(""); } }
public HostAgentClient(ISecurityToken credential, int port = 8000) { // subject = provider:user/1 // issuer = https://provider/ this.credential = credential ?? throw new ArgumentNullException(nameof(credential)); this.port = port; }
public override TokenInfo getTokenInfo(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName) { ++accessTokenLookupCount; BasicOAuthStoreTokenIndex tokenKey = MakeBasicOAuthStoreTokenIndex(securityToken, serviceName, tokenName); return(tokens.ContainsKey(tokenKey)?tokens[tokenKey]:null); }
public override void setTokenInfo(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName, TokenInfo tokenInfo) { ++accessTokenAddCount; BasicOAuthStoreTokenIndex tokenKey = MakeBasicOAuthStoreTokenIndex(securityToken, serviceName, tokenName); tokens.Add(tokenKey, tokenInfo); }
public void Index() { HttpRequest request = System.Web.HttpContext.Current.Request; HttpResponse response = System.Web.HttpContext.Current.Response; string method = request.HttpMethod; if (method == "POST") { ISecurityToken token = getSecurityToken(System.Web.HttpContext.Current, Request.RawUrl); if (token == null) { sendSecurityError(response); return; } setCharacterEncodings(request, response); Response.ContentType = "application/json"; try { String content; using (StreamReader reader = new StreamReader(Request.InputStream)) { content = reader.ReadToEnd(); } if ((content.IndexOf('[') != -1) && content.IndexOf('[') < content.IndexOf('{')) { // Is a batch JsonArray batch = JsonConvert.Import(content) as JsonArray; dispatchBatch(batch, response, token); } else { JsonObject requestObj = JsonConvert.Import(content) as JsonObject; dispatch(requestObj, response, token); } } catch (Exception je) { sendBadRequest(je, response); } } else if (method == "GET") { ISecurityToken token = getSecurityToken(System.Web.HttpContext.Current, Request.RawUrl); if (token == null) { sendSecurityError(response); return; } setCharacterEncodings(request, response); JsonObject requestObj = JsonConversionUtil.FromRequest(request); dispatch(requestObj, response, token); } }
/** * Get the set of user id's for a set of users and a group */ private HashSet <String> GetIdSet(HashSet <UserId> users, GroupId group, ISecurityToken token) { HashSet <String> ids = new HashSet <string>(); foreach (UserId user in users) { ids.UnionWith(GetIdSet(user, group, token)); } return(ids); }
/** * Creates a set of all configuration needed to satisfy the requested feature set. * * Appends special configuration for gadgets.util.hasFeature and gadgets.util.getFeatureParams to * the output js. * * This can't be handled via the normal configuration mechanism because it is something that * varies per request. * * @param reqs The features needed to satisfy the request. * @throws GadgetException If there is a problem with the gadget auth token */ private String GetLibraryConfig(Gadget gadget, ICollection <GadgetFeature> reqs) { GadgetContext context = gadget.getContext(); JsonObject features = containerConfig.GetJsonObject(context.getContainer(), FEATURES_KEY); Dictionary <String, Object> config = new Dictionary <string, object>(features == null ? 2 : features.Names.Count + 2); if (features != null) { // Discard what we don't care about. foreach (GadgetFeature feature in reqs) { String name = feature.getName(); Object conf = features.Opt(name); if (conf != null) { config.Add(name, conf); } } } // Add gadgets.util support. This is calculated dynamically based on request inputs. ModulePrefs prefs = gadget.getSpec().getModulePrefs(); var values = prefs.getFeatures().Values; Dictionary <String, Dictionary <String, String> > featureMap = new Dictionary <string, Dictionary <string, string> >(values.Count); foreach (Feature feature in values) { featureMap.Add(feature.getName(), feature.getParams()); } config.Add("core.util", featureMap); // Add authentication token config ISecurityToken authToken = context.getToken(); if (authToken != null) { Dictionary <String, String> authConfig = new Dictionary <String, String>(2); String updatedToken = authToken.getUpdatedToken(); if (updatedToken != null) { authConfig.Add("authToken", updatedToken); } String trustedJson = authToken.getTrustedJson(); if (trustedJson != null) { authConfig.Add("trustedJson", trustedJson); } config.Add("shindig.auth", authConfig); } return("gadgets.config.init(" + JsonConvert.ExportToString(config) + ");\n"); }
private static BasicOAuthStoreTokenIndex MakeBasicOAuthStoreTokenIndex(ISecurityToken securityToken, String serviceName, String tokenName) { BasicOAuthStoreTokenIndex tokenKey = new BasicOAuthStoreTokenIndex(); tokenKey.setGadgetUri(securityToken.getAppUrl()); tokenKey.setModuleId(securityToken.getModuleId()); tokenKey.setServiceName(serviceName); tokenKey.setTokenName(tokenName); tokenKey.setUserId(securityToken.getViewerId()); return(tokenKey); }
public async Task <IEnumerable <T> > ReadAsync( CancellationToken cancellationToken, ISecurityToken securityToken, string content) { return(await ReadAsync( cancellationToken, securityToken, content, Encoding.UTF8).ConfigureAwait(false)); }
/** * Encodes a token using the a plaintext dummy format. */ public String encodeToken(ISecurityToken token) { StringBuilder sb = new StringBuilder(); sb.Append(HttpUtility.UrlEncode(token.getOwnerId(), Encoding.UTF8)).Append(':') .Append(HttpUtility.UrlEncode(token.getViewerId(), Encoding.UTF8)).Append(':') .Append(HttpUtility.UrlEncode(token.getAppId(), Encoding.UTF8)).Append(':') .Append(HttpUtility.UrlEncode(token.getDomain(), Encoding.UTF8)).Append(':') .Append(HttpUtility.UrlEncode(token.getAppUrl(), Encoding.UTF8)).Append(':') .Append(token.getModuleId().ToString()).Append(':') .Append(HttpUtility.UrlEncode(token.getContainer(), Encoding.UTF8)); return sb.ToString(); }
protected virtual async Task <HttpResponseMessage> RequestContent( CancellationToken cancellationToken, ISecurityToken securityToken, ITimeOutPolicy policy, IRequest request, string requestUri, StringContent content) { try { using (var client = GetClient(securityToken, policy)) { switch (request.Verb) { case HttpVerb.Get: return(await client.GetAsync(requestUri + request.Content, cancellationToken).ConfigureAwait(false)); case HttpVerb.Post: return(await client.PostAsync(requestUri, content, cancellationToken).ConfigureAwait(false)); case HttpVerb.Put: return(await client.PutAsync(requestUri, content, cancellationToken).ConfigureAwait(false)); case HttpVerb.Delete: return(await client.DeleteAsync(requestUri + request.Content, cancellationToken).ConfigureAwait(false)); default: return(null); } } } catch (OperationCanceledException operationCanceledException) { Logger.LogWarning($"Operation cancelled: {operationCanceledException.Message}."); throw; } catch (System.Runtime.InteropServices.COMException exception) { Logger.LogCritical($"Operation cancelled: {exception.Message}."); throw; } catch (HttpRequestException exception) { Logger.LogCritical($"Operation cancelled: {exception.Message}."); throw; } catch (Exception exception) { Logger.LogCritical($"Operation cancelled: {exception.Message}."); throw; } }
public RpcRequestItem(JsonObject rpc, ISecurityToken token, BeanConverter converter) : base(getService(rpc["method"].ToString()), getOperation(rpc["method"].ToString()), token, converter) { if (rpc.Contains("params")) { data = rpc["params"] as JsonObject; } else { data = new JsonObject(); } }
/** * Encodes a token using the a plaintext dummy format. */ public String encodeToken(ISecurityToken token) { StringBuilder sb = new StringBuilder(); sb.Append(HttpUtility.UrlEncode(token.getOwnerId(), Encoding.UTF8)).Append(':') .Append(HttpUtility.UrlEncode(token.getViewerId(), Encoding.UTF8)).Append(':') .Append(HttpUtility.UrlEncode(token.getAppId(), Encoding.UTF8)).Append(':') .Append(HttpUtility.UrlEncode(token.getDomain(), Encoding.UTF8)).Append(':') .Append(HttpUtility.UrlEncode(token.getAppUrl(), Encoding.UTF8)).Append(':') .Append(token.getModuleId().ToString()).Append(':') .Append(HttpUtility.UrlEncode(token.getContainer(), Encoding.UTF8)); return(sb.ToString()); }
/** * Remove an access token for the given user/gadget/service/token name */ public void removeToken(ISecurityToken securityToken, OAuthStore.ConsumerInfo consumerInfo, OAuthArguments arguments, OAuthResponseParams responseParams) { try { store.removeToken(securityToken, consumerInfo, arguments.getServiceName(), arguments.getTokenName()); } catch (GadgetException e) { throw responseParams.oauthRequestException(OAuthError.UNKNOWN_PROBLEM, "Unable to remove access token", e); } }
public async Task <string> GetString( CancellationToken cancellationToken, ISecurityToken securityToken, ITimeOutPolicy policy, IRequest request) { var response = await RequestContent( cancellationToken, securityToken, policy, request).ConfigureAwait(false); return(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); }
protected static String getTokenOwner(sRequest request) { ISecurityToken st = request.getSecurityToken(); if (request.AuthType != AuthType.NONE && st.getOwnerId() != null && st.getOwnerId().Equals(st.getViewerId()) && request.getOAuthArguments().mayUseToken()) { return(st.getOwnerId()); } // Requests that don't use authentication can share the result. return(DEFAULT_KEY_VALUE); }
public async Task <IEnumerable <T> > ReadAsync <T>( CancellationToken cancellationToken, ISecurityToken securityToken, ITimeOutPolicy policy, string content, string route) { return(await ReadAsync <T>( cancellationToken, securityToken, policy, content, route, Encoding.UTF8).ConfigureAwait(false)); }
public async Task <IEnumerable <T> > ReadAsync <T>( CancellationToken cancellationToken, ISecurityToken securityToken, ITimeOutPolicy policy, string content, Encoding encoding) { return(await ReadAsync <T>( cancellationToken, securityToken, policy, content, typeof(T).Name, encoding).ConfigureAwait(false)); }
/** * Figure out the OAuth token that should be used with this request. We check for this in three * places. In order of priority: * * 1) From information we cached on the client. * We encrypt the token and cache on the client for performance. * * 2) From information we have in our persistent state. * We persist the token server-side so we can look it up if necessary. * * 3) From information the gadget developer tells us to use (a preapproved request token.) * Gadgets can be initialized with preapproved request tokens. If the user tells the service * provider they want to add a gadget to a gadget container site, the service provider can * create a preapproved request token for that site and pass it to the gadget as a user * preference. * @throws GadgetException */ private void lookupToken(ISecurityToken securityToken, OAuthStore.ConsumerInfo consumerInfo, OAuthArguments arguments, OAuthClientState clientState, AccessorInfoBuilder accessorBuilder, OAuthResponseParams responseParams) { if (clientState.getRequestToken() != null) { // We cached the request token on the client. accessorBuilder.setRequestToken(clientState.getRequestToken()); accessorBuilder.setTokenSecret(clientState.getRequestTokenSecret()); } else if (clientState.getAccessToken() != null) { // We cached the access token on the client accessorBuilder.setAccessToken(clientState.getAccessToken()); accessorBuilder.setTokenSecret(clientState.getAccessTokenSecret()); accessorBuilder.setSessionHandle(clientState.getSessionHandle()); accessorBuilder.setTokenExpireMillis(clientState.getTokenExpireMillis()); } else { // No useful client-side state, check persistent storage OAuthStore.TokenInfo tokenInfo; try { tokenInfo = store.getTokenInfo(securityToken, consumerInfo, arguments.getServiceName(), arguments.getTokenName()); } catch (GadgetException e) { throw responseParams.oauthRequestException(OAuthError.UNKNOWN_PROBLEM, "Unable to retrieve access token", e); } if (tokenInfo != null && tokenInfo.getAccessToken() != null) { // We have an access token in persistent storage, use that. accessorBuilder.setAccessToken(tokenInfo.getAccessToken()); accessorBuilder.setTokenSecret(tokenInfo.getTokenSecret()); accessorBuilder.setSessionHandle(tokenInfo.getSessionHandle()); accessorBuilder.setTokenExpireMillis(tokenInfo.getTokenExpireMillis()); } else { // We don't have an access token yet, but the client sent us a (hopefully) preapproved // request token. accessorBuilder.setRequestToken(arguments.getRequestToken()); accessorBuilder.setTokenSecret(arguments.getRequestTokenSecret()); } } }
/** * Retrieve an AccessorInfo and OAuthAccessor that are ready for signing OAuthMessages. To do * this, we need to figure out: * * - what consumer key/secret to use for signing. * - if an access token should be used for the request, and if so what it is. * * - the OAuth request/authorization/access URLs. * - what HTTP method to use for request token and access token requests * - where the OAuth parameters are located. * * Note that most of that work gets skipped for signed fetch, we just look up the consumer key * and secret for that. Signed fetch always sticks the parameters in the query string. */ public AccessorInfo getOAuthAccessor(ISecurityToken securityToken, OAuthArguments arguments, OAuthClientState clientState, OAuthResponseParams responseParams) { AccessorInfoBuilder accessorBuilder = new AccessorInfoBuilder(); // Does the gadget spec tell us any details about the service provider, like where to put the // OAuth parameters and what methods to use for their URLs? OAuthServiceProvider provider = null; if (arguments.mayUseToken()) { provider = lookupSpecInfo(securityToken, arguments, accessorBuilder, responseParams); } else { // This is plain old signed fetch. accessorBuilder.setParameterLocation(AccessorInfo.OAuthParamLocation.URI_QUERY); } // What consumer key/secret should we use? OAuthStore.ConsumerInfo consumer; try { consumer = store.getConsumerKeyAndSecret( securityToken, arguments.getServiceName(), provider); accessorBuilder.setConsumer(consumer); } catch (GadgetException e) { throw responseParams.oauthRequestException(OAuthError.UNKNOWN_PROBLEM, "Unable to retrieve consumer key", e); } // Should we use the OAuth access token? We never do this unless the client allows it, and // if owner == viewer. if (arguments.mayUseToken() && securityToken.getOwnerId() != null && securityToken.getViewerId().Equals(securityToken.getOwnerId())) { lookupToken(securityToken, consumer, arguments, clientState, accessorBuilder, responseParams); } return accessorBuilder.create(responseParams); }
/** * Set the security token for the request. * * @param token The security token * @return This object */ public AuthInfo setSecurityToken(ISecurityToken token) { context.Items[url + Attribute.SECURITY_TOKEN] = token; return this; }
private GadgetSpec findSpec(ISecurityToken securityToken, OAuthArguments arguments, OAuthResponseParams responseParams) { try { return specFactory.getGadgetSpec(new Uri(securityToken.getAppUrl()), arguments.getBypassSpecCache()); } catch (UriFormatException e) { throw responseParams.oauthRequestException(OAuthError.UNKNOWN_PROBLEM, "Could not fetch gadget spec, gadget URI invalid.", e); } catch (GadgetException e) { throw responseParams.oauthRequestException(OAuthError.UNKNOWN_PROBLEM, "Could not fetch gadget spec", e); } }
/** * Remove the access token for the given user/gadget/service/token */ public abstract void removeToken(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName);
/** * Create response parameters. */ public OAuthResponseParams(ISecurityToken securityToken, sRequest originalRequest, BlobCrypter stateCrypter) { this.securityToken = securityToken; this.originalRequest = originalRequest; newClientState = new OAuthClientState(stateCrypter); }
/// <summary> /// Clone an existing HttpRequest. /// </summary> /// public sRequest(sRequest srequest) { req = srequest.req; uri = srequest.uri; ignoreCache = srequest.ignoreCache; cacheTtl = srequest.cacheTtl; gadget = srequest.gadget; container = srequest.container; securityToken = srequest.securityToken; if (srequest.postBody != null) { postBody = new byte[srequest.postBody.Length]; Array.Copy(srequest.postBody, postBody, srequest.postBody.Length); } if (srequest.oauthArguments != null) { oauthArguments = new OAuthArguments(srequest.oauthArguments); } authType = srequest.authType; rewriteMimeType = srequest.rewriteMimeType; followRedirects = srequest.followRedirects; }
/** * Set the access token for the given user/gadget/service/token */ public abstract void setTokenInfo(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName, TokenInfo tokenInfo);
/** * Format a response as JSON, including additional JSON inserted by * chained content fetchers. */ private String convertResponseToJson(ISecurityToken authToken, HttpRequestWrapper request, sResponse results) { try { String originalUrl = request.getParameter(URL_PARAM); String body = results.responseString; if ("FEED".Equals(request.getParameter(CONTENT_TYPE_PARAM))) { body = processFeed(originalUrl, request, body); } JsonObject resp = FetchResponseUtils.getResponseAsJson(results, body); if (authToken != null) { String updatedAuthToken = authToken.getUpdatedToken(); if (updatedAuthToken != null) { resp.Put("st", updatedAuthToken); } } // Use raw param as key as URL may have to be decoded return new JsonObject().Put(originalUrl, resp).ToString(); } catch (JsonException) { return ""; } }
/** * Lookup information contained in the gadget spec. */ private OAuthServiceProvider lookupSpecInfo(ISecurityToken securityToken, OAuthArguments arguments, AccessorInfoBuilder accessorBuilder, OAuthResponseParams responseParams) { GadgetSpec spec = findSpec(securityToken, arguments, responseParams); OAuthSpec oauthSpec = spec.getModulePrefs().getOAuthSpec(); if (oauthSpec == null) { throw responseParams.oauthRequestException(OAuthError.BAD_OAUTH_CONFIGURATION, "Failed to retrieve OAuth URLs, spec for gadget " + securityToken.getAppUrl() + " does not contain OAuth element."); } OAuthService service = oauthSpec.getServices()[arguments.getServiceName()]; if (service == null) { throw responseParams.oauthRequestException(OAuthError.BAD_OAUTH_CONFIGURATION, "Failed to retrieve OAuth URLs, spec for gadget does not contain OAuth service " + arguments.getServiceName() + ". Known services: " + String.Join(",",oauthSpec.getServices().Keys.AsEnumerable().ToArray()) + '.'); } // In theory some one could specify different parameter locations for request token and // access token requests, but that's probably not useful. We just use the request token // rules for everything. accessorBuilder.setParameterLocation(getStoreLocation(service.getRequestUrl().location, responseParams)); accessorBuilder.setMethod(getStoreMethod(service.getRequestUrl().method, responseParams)); OAuthServiceProvider provider = new OAuthServiceProvider( service.getRequestUrl().url.ToString(), service.getAuthorizationUrl().ToString(), service.getAccessUrl().url.ToString()); return provider; }
private void dispatch(JsonObject request, HttpResponse servletResponse, ISecurityToken token) { String key = null; if (request.Contains("id")) { key = request["id"] as String; } RpcRequestItem requestItem = new RpcRequestItem(request, token, jsonConverter); // Resolve each Future into a response. // TODO: should use shared deadline across each request ResponseItem response = getResponseItem(HandleRequestItem(requestItem)); Object result = getJsonResponse(key, response, requestItem); servletResponse.Output.Write(jsonConverter.ConvertToString(result)); }
protected void dispatchBatch(JsonArray batch, HttpResponse response, ISecurityToken token) { // Use linked hash map to preserve order List<IAsyncResult> responses = new List<IAsyncResult>(batch.Length); // Gather all Futures. We do this up front so that // the first call to get() comes after all futures are created, // which allows for implementations that batch multiple Futures // into single requests. for (int i = 0; i < batch.Length; i++) { JsonObject batchObj = batch.GetObject(i); RpcRequestItem requestItem = new RpcRequestItem(batchObj, token, jsonConverter); responses.Add(HandleRequestItem(requestItem)); } // Resolve each Future into a response. // TODO: should use shared deadline across each request List<Object> result = new List<object>(); for (int i = 0; i < batch.Length; i++) { JsonObject batchObj = batch.GetObject(i); String key = null; if (batchObj.Contains("id")) { key = batchObj["id"] as String; } result.Add(getJsonResponse(key, getResponseItem(responses[i]), null)); } response.Output.Write(jsonConverter.ConvertToString(result)); }
/** * Remove an access token for the given user/gadget/service/token name */ public void removeToken(ISecurityToken securityToken, OAuthStore.ConsumerInfo consumerInfo, OAuthArguments arguments, OAuthResponseParams responseParams) { try { store.removeToken(securityToken, consumerInfo, arguments.getServiceName(), arguments.getTokenName()); } catch (GadgetException e) { throw responseParams.oauthRequestException(OAuthError.UNKNOWN_PROBLEM, "Unable to remove access token", e); } }
public override void removeToken(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName) { ++accessTokenRemoveCount; BasicOAuthStoreTokenIndex tokenKey = MakeBasicOAuthStoreTokenIndex(securityToken, serviceName, tokenName); tokens.Remove(tokenKey); }
/** * Returns a list of people that correspond to the passed in person ids. * * @param userIds A set of users * @param groupId The group * @param collectionOptions How to filter, sort and paginate the collection being fetched * @param fields The profile details to fetch. Empty set implies all * @param token The gadget token @return a list of people. */ abstract public RestfulCollection<Person> getPeople(HashSet<UserId> userIds, GroupId groupId, CollectionOptions collectionOptions, HashSet<String> fields, ISecurityToken token);
private void handleSingleRequest(HttpRequest servletRequest, HttpResponse servletResponse, ISecurityToken token, BeanConverter converter) { RestfulRequestItem requestItem = new RestfulRequestItem(servletRequest, token, converter); var asyncResult = HandleRequestItem(requestItem); // handle just the one case where we can't find a handler if (asyncResult == null) { sendError(servletResponse, new ResponseItem((int)HttpStatusCode.InternalServerError, "The service " + requestItem.getService() + " is not implemented")); return; } ResponseItem responseItem = getResponseItem(asyncResult); servletResponse.ContentType = converter.GetContentType(); if (responseItem.getErrorCode() >= 200 && responseItem.getErrorCode() < 400) { Object resp = responseItem.getResponse(); // put single object responses into restfulcollection if (!(resp is DataCollection) && !(resp is IRestfulCollection)) { switch (requestItem.getService()) { case IHandlerDispatcher.ACTIVITY_ROUTE: if (resp is Activity) { resp = new RestfulCollection<Activity>((Activity)resp); } break; case IHandlerDispatcher.PEOPLE_ROUTE: if (resp is Person) { resp = new RestfulCollection<Person>((Person)resp); } break; case IHandlerDispatcher.APPDATA_ROUTE: if (requestItem.getOperation() != "POST") resp = new DataCollection(new Dictionary<string, Dictionary<string, string>> { { "entry", (Dictionary<string, string>)resp } }); break; default: resp = new Dictionary<string, object> { { "entry", resp } }; break; } } servletResponse.Output.Write(converter.ConvertToString(resp, requestItem)); } else { sendError(servletResponse, responseItem); } }
/** * Retrieve OAuth consumer to use for requests. The returned consumer is ready to use for signed * fetch requests. * * @param securityToken token for user/gadget making request. * @param serviceName gadget's nickname for the service being accessed. * @param provider OAuth service provider info to be inserted into the returned consumer. * * @throws GadgetException if no OAuth consumer can be found (e.g. no consumer key can be used.) */ public abstract ConsumerInfo getConsumerKeyAndSecret(ISecurityToken securityToken, String serviceName, OAuthServiceProvider provider);
/** * Figure out the OAuth token that should be used with this request. We check for this in three * places. In order of priority: * * 1) From information we cached on the client. * We encrypt the token and cache on the client for performance. * * 2) From information we have in our persistent state. * We persist the token server-side so we can look it up if necessary. * * 3) From information the gadget developer tells us to use (a preapproved request token.) * Gadgets can be initialized with preapproved request tokens. If the user tells the service * provider they want to add a gadget to a gadget container site, the service provider can * create a preapproved request token for that site and pass it to the gadget as a user * preference. * @throws GadgetException */ private void lookupToken(ISecurityToken securityToken, OAuthStore.ConsumerInfo consumerInfo, OAuthArguments arguments, OAuthClientState clientState, AccessorInfoBuilder accessorBuilder, OAuthResponseParams responseParams) { if (clientState.getRequestToken() != null) { // We cached the request token on the client. accessorBuilder.setRequestToken(clientState.getRequestToken()); accessorBuilder.setTokenSecret(clientState.getRequestTokenSecret()); } else if (clientState.getAccessToken() != null) { // We cached the access token on the client accessorBuilder.setAccessToken(clientState.getAccessToken()); accessorBuilder.setTokenSecret(clientState.getAccessTokenSecret()); accessorBuilder.setSessionHandle(clientState.getSessionHandle()); accessorBuilder.setTokenExpireMillis(clientState.getTokenExpireMillis()); } else { // No useful client-side state, check persistent storage OAuthStore.TokenInfo tokenInfo; try { tokenInfo = store.getTokenInfo(securityToken, consumerInfo, arguments.getServiceName(), arguments.getTokenName()); } catch (GadgetException e) { throw responseParams.oauthRequestException(OAuthError.UNKNOWN_PROBLEM, "Unable to retrieve access token", e); } if (tokenInfo != null && tokenInfo.getAccessToken() != null) { // We have an access token in persistent storage, use that. accessorBuilder.setAccessToken(tokenInfo.getAccessToken()); accessorBuilder.setTokenSecret(tokenInfo.getTokenSecret()); accessorBuilder.setSessionHandle(tokenInfo.getSessionHandle()); accessorBuilder.setTokenExpireMillis(tokenInfo.getTokenExpireMillis()); } else { // We don't have an access token yet, but the client sent us a (hopefully) preapproved // request token. accessorBuilder.setRequestToken(arguments.getRequestToken()); accessorBuilder.setTokenSecret(arguments.getRequestTokenSecret()); } } }
/** * Retrieve OAuth access token to use for the request. * @param securityToken token for user/gadget making request. * @param consumerInfo OAuth consumer that will be used for the request. * @param serviceName gadget's nickname for the service being accessed. * @param tokenName gadget's nickname for the token to use. * @return the token and secret, or null if none exist * @throws GadgetException if an error occurs during lookup */ public abstract TokenInfo getTokenInfo(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName);
public override TokenInfo getTokenInfo(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName) { ++accessTokenLookupCount; BasicOAuthStoreTokenIndex tokenKey = MakeBasicOAuthStoreTokenIndex(securityToken, serviceName, tokenName); return tokens.ContainsKey(tokenKey)?tokens[tokenKey]:null; }
public override void setTokenInfo(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName, TokenInfo tokenInfo) { ++accessTokenAddCount; BasicOAuthStoreTokenIndex tokenKey = MakeBasicOAuthStoreTokenIndex(securityToken, serviceName, tokenName); tokens.Add(tokenKey, tokenInfo); }
/** * Returns a person that corresponds to the passed in person id. * * @param id The id of the person to fetch. * @param fields The fields to fetch. * @param token The gadget token * @return a list of people. */ abstract public Person getPerson(UserId id, HashSet<String> fields, ISecurityToken token);
public override ConsumerInfo getConsumerKeyAndSecret(ISecurityToken securityToken, String serviceName, OAuthServiceProvider provider) { ++consumerKeyLookupCount; BasicOAuthStoreConsumerIndex pk = new BasicOAuthStoreConsumerIndex(); pk.setGadgetUri(securityToken.getAppUrl()); pk.setServiceName(serviceName); BasicOAuthStoreConsumerKeyAndSecret cks = consumerInfos.ContainsKey(pk) ? consumerInfos[pk] : defaultKey; if (cks == null) { throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, "No key for gadget " + securityToken.getAppUrl() + " and service " + serviceName); } OAuthConsumer consumer; if (cks.keyType == BasicOAuthStoreConsumerKeyAndSecret.KeyType.RSA_PRIVATE) { consumer = new OAuthConsumer(null, cks.ConsumerKey, null, provider); consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.RSA_SHA1); consumer.setProperty(RSA_SHA1.X509_CERTIFICATE, cks.CertName); consumer.setProperty(RSA_SHA1.X509_CERTIFICATE_PASS, cks.CertPass); } else { consumer = new OAuthConsumer(null, cks.ConsumerKey, cks.ConsumerSecret, provider); consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1); } return new ConsumerInfo(consumer, cks.ConsumerKey); }
/// <summary> /// Assign the security token to use for making any form of authenticated /// request. /// </summary> /// public sRequest setSecurityToken(ISecurityToken _securityToken) { securityToken = _securityToken; return this; }
private static BasicOAuthStoreTokenIndex MakeBasicOAuthStoreTokenIndex(ISecurityToken securityToken, String serviceName, String tokenName) { BasicOAuthStoreTokenIndex tokenKey = new BasicOAuthStoreTokenIndex(); tokenKey.setGadgetUri(securityToken.getAppUrl()); tokenKey.setModuleId(securityToken.getModuleId()); tokenKey.setServiceName(serviceName); tokenKey.setTokenName(tokenName); tokenKey.setUserId(securityToken.getViewerId()); return tokenKey; }