logo
down
shadow

Freebase oAuth2 Bad Request(400) .Net


Freebase oAuth2 Bad Request(400) .Net

By : user2948759
Date : November 15 2020, 06:54 AM
I wish this helpful for you You're including the Content-Type in the POST data but it should be presented as part of the HTTP headers as in:
code :
wb.Headers.Add("Content-Type","application/x-www-form-urlencoded");
data2["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer";
public class GoogleServiceAccountBearerJWTSample
{
    private static string Base64UrlEncode(byte[] input)
    {
        var output = Convert.ToBase64String(input);
        output = output.Split('=')[0]; // Remove any trailing '='s
        output = output.Replace('+', '-'); // 62nd char of encoding
        output = output.Replace('/', '_'); // 63rd char of encoding
        return output;
    }

    public static string Encode(object payload, AsymmetricAlgorithm rsa) {
        var segments = new List<string>();
        var header = new { alg = "RS256", typ = "JWT" };
        byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Formatting.None));
        byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None));
        segments.Add(Base64UrlEncode(headerBytes));
        segments.Add(Base64UrlEncode(payloadBytes));
        var stringToSign = string.Join(".", segments.ToArray());
        var bytesToSign = Encoding.UTF8.GetBytes(stringToSign);

        // VARIANT A - should work on non-SHA256 enabled systems
        var rs = rsa as RSACryptoServiceProvider;
        var cspParam = new CspParameters
        {
            KeyContainerName = rs.CspKeyContainerInfo.KeyContainerName,
            KeyNumber = rs.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2
        };
        var aescsp = new RSACryptoServiceProvider(cspParam) { PersistKeyInCsp = false };
        var signature = aescsp.SignData(bytesToSign, "SHA256");
        // END OF VARIANT A

        // VARIANT B - works on FIPS SHA256 enabled systems
        // var pkcs1 = new RSAPKCS1SignatureFormatter(rsa);
        // pkcs1.SetHashAlgorithm("SHA256");
        // var signature = pkcs1.CreateSignature(new SHA256Managed().ComputeHash(bytesToSign));
        // END OF VARIANT B

        segments.Add(Base64UrlEncode(signature));
        return string.Join(".", segments.ToArray());
   }

   public static void Main()
   {    
        var utc0 = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
        var issueTime = DateTime.UtcNow;

        var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
        var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds; // Expiration time is up to 1 hour, but lets play on safe side

        var payload = new {
            iss = "xxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com",
            aud = "https://www.googleapis.com/oauth2/v3/token",
            scope = "https://www.googleapis.com/auth/freebase",
            exp = exp,
            iat = iat
        };

        var certificate = new X509Certificate2("google-client.p12", "notasecret");
        var signedJwt = Encode(payload, certificate.PrivateKey);

        //System.Console.WriteLine(signedJwt);

        using (var wb = new WebClient())
        {
            var url = "https://www.googleapis.com/oauth2/v3/token";
            var data2 = new NameValueCollection();
            data2["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer";
            data2["assertion"] = signedJwt;
            var response2 = wb.UploadValues(url, "POST", data2);
            System.Console.WriteLine(Encoding.UTF8.GetString(response2));
        }
    }
}


Share : facebook icon twitter icon
ActiveResource choking on freebase json request

ActiveResource choking on freebase json request


By : Akshat Verma
Date : March 29 2020, 07:55 AM
hope this fix your issue The problem is that the JSON returned isn't formed the way ActiveResource expects it to be. ARes doesn't expect all of that metadata that is being returned, it is only expecting what is in the results portion of the response.
To be explicit, you're getting back:
code :
{"status":"200 OK","result":[{"mid":"/m/05b3c","name":"Nirvana","notable":{"name" ...
[{"mid":"/m/05b3c","name":"Nirvana","notable":{"name"...
class Freebase < ActiveResource::Base

  self.site = "https://www.googleapis.com/"
  self.format = :json

  def self.search(word)
    self.find(:all, :from => "/freebase/v1/search/", :params => { :query => word })
  end

  private

  def self.find_every(options)
    begin
      case from = options[:from]
      when Symbol
        instantiate_collection(get(from, options[:params]))
      when String
        path = "#{from}#{query_string(options[:params])}"
        instantiate_collection(format.decode(connection.get(path, headers).body['result']) || [])
      else
        prefix_options, query_options = split_options(options[:params])
        path = collection_path(prefix_options, query_options)
        instantiate_collection( (format.decode(connection.get(path, headers).body['result']) || []), prefix_options )
      end
    rescue ActiveResource::ResourceNotFound
      # Swallowing ResourceNotFound exceptions and return nil - as per
      # ActiveRecord.
      nil
    end
  end

end
Array of Freebase MIDs and sending multiple queries to freebase

Array of Freebase MIDs and sending multiple queries to freebase


By : Hal
Date : March 29 2020, 07:55 AM
will help you Your $query_array should just be an associative array of queries by name rather than an array of associative arrays. So instead of this:
code :
$q_array = array('q'.$count=>array('query'=>$simple_query));
array_push ($query_array, $q_array );
$q_array = array('query'=>$simple_query);
$query_array['q'.$count] = $q_array;
[{
  "mid": null,
  "name": null,
  "topics:mid|=":[
    "/m/045c7b",
    "/m/0d6lp",
    "/m/021ympy",
    ...
    ]
}]
Simple request using googleapis to freebase

Simple request using googleapis to freebase


By : Luis Pachas
Date : March 29 2020, 07:55 AM
To fix the issue you can do Here is how you build MQL queries for Freebase topics:
Find a sample topic that meets you query (ex. Madonna)
Is there a freebase dump that lets me access the schema of Freebase

Is there a freebase dump that lets me access the schema of Freebase


By : Larry Ho
Date : March 29 2020, 07:55 AM
I hope this helps . All of the schema is included in the RDF dump. Expected type is available as type.property.expected_type e.g.
code :
ns:people.person.date_of_birth  ns:type.property.expected_type  ns:type.datetime.
implementing oauth2 in compojure, how do I wait for the second oauth2 callback before responding to the user's request?

implementing oauth2 in compojure, how do I wait for the second oauth2 callback before responding to the user's request?


By : user2853832
Date : March 29 2020, 07:55 AM
it should still fix some issue Based on the documentation for Google's OAuth2 for web servers here, the flow consists of the following steps:
Your application redirects a browser to a Google URL; the URL includes query parameters that indicate the type of access being requested. The result is an authorization code, which Google returns to your application in a query string. After receiving the authorization code, your application can exchange the code (along with a client ID and client secret) for an access token and, in some cases, a refresh token.
code :
(defn callback
  "Handles the callback from GitHub OAuth flow."
  [code]
  (let [params {:form-params {:client_id client-id
                              :client_secret client-secret
                              :code code}}
        {:keys [body]} (client/post access-token-url params) ;; This is doing the POST
                                                             ;; request to GitHub.
        token  ((qs-map body) "access_token")]               ;; Getting the token from 
                                                             ;; the response here. 
    {:status 302
     :headers {"location" "/repos"
               "set-cookie" (str "token=" token ";Path=/")}}))
Related Posts Related Posts :
  • Parsing string with nested separators
  • How to invoke a DLL method from PowerShell 1.0
  • Starting Web Api 2 with OWIN
  • display a string with multiple lines in TextBox
  • Is it possible to programmatically get a shared Dropbox link without sending the user to the dropbox login page?
  • HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation\TimeZoneKeyName corrupt?
  • Performance cost of creating array of constants as function argument
  • SQL Server rowversion and order
  • Type.GetType returns null when called via COM interop
  • Is the Microsoft.Practices.EnterpriseLibrary.Validation outdated?
  • .net Bitmap changes color of image
  • vb.net reading text file ,split to random range
  • LINQ Join with same Name on different tables
  • Programmatically share a dropbox link in .net without having user login to Dropbox
  • bootstrapper fails to install .Net Framework 4.0
  • Why would signing credentials from a RSA-SHA512 X509Certificate2 appear to be RSA-SHA256?
  • Using .NET Class as the DataSource with SSRS RDLC
  • Choosing SQL Server version for new project
  • WCF FileNotFoundException
  • Fullcalendar ignoring all options on initialization?
  • Why does InlineCollection not offer an Indexer (without casting)?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org